Consider the following two routes
<Route path="/:username" component={Profile} />
<Route path="*" component={NotFound} />
I'm aware the path /:username
would always match even for a user that does not exist so I am trying the following
<Route
path="/:username"
render={({ match }) => {
return userExists(match.params.username) ?
<Profile match={match} /> : <NotFound match={match} />;
}}
/>
userExists()
being a function that returns true
or false
after making a call to the database to check if the user with the given username exists.
Am I handling this in the completely wrong way? It feels funny to have such a function in my route handler.
It's not wrong. What you are essentially doing is rendering a stateless functional component: https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components
It depends on the overall structure and needs of your app whether or not this functional component should be defined in a separate file, but it's perfectly fine to conditionally return React elements in functional components.
To further illustrate the symmetry between functions and Components in React, consider the alternative approach in which you pass a function as the "component" param: (note the use of implicit return with arrow functions)
<Route
path="/:username"
component={({ match }) => userExists(match.params.username) ?
<Profile match={match} /> : <NotFound match={match} />
}}
/>
由于userExists
被定义为异步的,我根本看不出代码是如何“正确”的,也就是说,我认为它不会起作用,而且我认为原始问题尚未解决。
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.