简体   繁体   中英

Is there a way to match routes in react-router-dom v6 based on whether the route exists in an object?

I recently migrated to react-router-dom v6, and there is one item I need to change which I am a bit confused with. Basically, I have routes at /projects/:id and I want to direct to <Project /> if id exists in an object called projects , and to otherwise direct to <NotFound /> .

I have this object:

 const projects = { sample: { // properties }, sample2: { // properties }, sample3: { // properties } }

But I am unsure how to check if the id in route matches any of the items in projects above, so I have the following, broken code:

 <Routes> <Route path="/" element={ <Home /> } /> <Route path="/about" element={ <About /> } /> <Route path="/projects/:id" element={ ({ match }) => ( match? <Project />: <NotFound /> )} /> <Route path="*" element={ <NotFound /> } /> </Routes>

Ideally, /projects/sample2 should be a valid route, rendering <Project /> , but /projects/sample5 should not be a valid route, and therefore it should direct to <NotFound /> .

But I'm not sure what prop should be used and matched, and how to do it:(

You can use params.id in projects in your Route or inside the Project component:

params.id in projects ? /* render project */ : <NotFound />
const isProject = !!Object.entries(projects).filter(sample=>sample[1].id ===id);

// provided that id is one of the keys in properties; 

element={isProject ? <Project /> : <NotFound /> }

You can try to changing in the following way:

<Routes>
  <Route path="/" element={ <Home /> } />
  <Route path="/about" element={ <About /> } />
  <Route path="/projects/:id" element={ <Project /> } />
  <Route path="/404" element={ <NotFound /> } />
  <Route path="*" element={<Navigate to="/404" replace />} />
</Routes>

In the Project component, you can use useEffect to redirect to NotFound page

const { id } = useParams();
const navigate = useNavigate();

...

useEffect(() => {
  if (/* ex: response.status == 404 || !id || ... */) {
    navigate("/notfound", { replace: true });
  }
}, [id, navigate]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM