如何在React的闭合JSX标签内实现加载完成后的条件判断与无数据跳转
Alright, let's work through adding that conditional logic to your React component. You want to check if there are any existing held items once data loading is done, and redirect to the creation page if there aren't any. Here's how to implement this properly:
Solution: Add Conditional Redirect After Loading Data
First, make sure you import the necessary hooks (we'll need React's useEffect and React Router's useNavigate for the redirect):
import { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; // Don't forget to import your existing components: Loader, Table, alternatefunctiontag
Next, modify your component to include the navigation hook and the conditional check. We'll use useEffect to trigger the check once loading completes:
const YourComponent = ({ id, resources, empty, columns, getItems }) => { const navigate = useNavigate(); // Check for held items and redirect after loading finishes useEffect(() => { // Only run once loading is complete (id is not empty) if (id !== "") { // Check if there are no held items (use your existing empty state or resources directly) const hasNoHeldItems = empty || (resources && resources.length === 0); if (hasNoHeldItems) { // Replace with your actual creation page route path navigate("/create-project"); } } }, [id, empty, resources, navigate]); // Re-run if any of these values change return ( <Loader empty={true} loading={id === ""}> {!empty ? <Table data={resources} columns={columns} loadData={getItems} queryObj={{ id: id }} searchEnabled={false} noHeader={true} customStyles={{ headCells: { style: { fontWeight: 'bold' }, }, }} /> : <alternatefunctiontag id={id} />} </Loader> ); }; export default YourComponent;
Key Breakdown:
useNavigate: This hook lets us programmatically redirect to the creation page when our condition is met.useEffectTrigger: The dependency array ([id, empty, resources, navigate]) ensures the check runs only when loading finishes (idis no longer empty) or when the data state changes.- Condition Logic: We first confirm loading is done, then check if there are no held items using either your existing
emptystate or directly checking theresourcesarray length.
Quick Notes:
- Adjust
"/create-project"to match the actual route path of your project creation page. - If your
emptystate is already based onresources, you can simplify the condition to justemptyinstead of checkingresources.length. - Make sure your app is set up with React Router (v6+) for the
useNavigatehook to work correctly.
内容的提问来源于stack exchange,提问作者Stephen Roche
相关产品推荐
相关产品推荐

