我有以下代码:
const PrivateRoute = ({ component: Component, ...rest }) => {
return (<Route {...rest} render={(props) => (isAuthenticated() === true ? <Component {...props} /> : <Redirect to='/login' /> )} />)
}
但我不明白这是怎么回事..我这样称呼它:
<PrivateRoute exact path = '/home' component={Home}></PrivateRoute>
它起作用了,我只是不理解它。道具是在哪里传入的?什么是组件:组件。
如果有人能解释一下这个组件是如何工作的,我将不胜感激。
发布于 2020-03-19 21:23:07
component: Component
为object destructuring
你可以用以下方式重写它:
const PrivateRoute = (props) => {
const Component = props.component;
//shallow copy props, can also do {...props}
const rest = Object.assign({},props);
//delete component property from rest
// this will not affect props becaus of the shallow copy
react-router Route组件将获取一个props.component,并使用所有传递给Route的道具减去props.component来呈现该组件。
您可以创建一个执行相同操作的PrivateRoute
,但它不会直接渲染传递到道具中的组件,而是会渲染路线并将渲染道具传递给它,该道具是在fly ()=>jsx
上创建的组件。Route将为您呈现此组件。
https://stackoverflow.com/questions/60757967
复制相似问题