简体   繁体   中英

Conditionally render 404 route with React Router v4

In my most parent component App I implemented my route like this:

<GetCustomerData />
<Switch>
    <Route path="/dashboard/:customerID" component={Dashboard} />
</Switch>

GetCustomerData gets the customer data as an array of JSON payload (including the customer ID). We navigate to Dashboard component for a specific customer with their corresponding ID.

I want to setup a route which basically throws a 404 component if the customer ID we pass in the URL doesn't exist in the JSON payload in GetCustomerData .

I've seen some tutorials that say to do something like:

 <Route path="*" component={NotFound} />

But this doesn't really check for the customerID param in the url. How do I implement this?

EDIT: In my main component I have Browser route configured in this way:

ReactDOM.render(
    <BrowserRouter>
        <div className="main">
            <App />
        </div>
    </BrowserRouter>
    ,
    document.getElementById('react-app')
);

First setup a 404 route

<Route path="/error" component={NotFound} />

Then store your GetCustomerData data in an array in state. It is unclear where the data comes from or how you can manipulate it from your example. If getting the data into the component state is a problem create a separate question.

If you are pulling the id from the URL then use the route parameter in props to get your customer id this.props.match.params.customerID

Once you have the data and the id handy then you can run a check in your render method.

if (this.state.data.includes(this.props.match.params.customerID)){
 return <whatYouExpectedToReturn/>
}else{
 return <Redirect to='/error'/>;
}

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