我有一个对象列表,其中有一个path
,一个name
和一个React component
作为属性。当我遍历对象列表,获取每个对象并渲染<Route key={indice} path={route.path} name={route.name} component={route.component}/>
组件时,我会收到警告:
Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`.
in Route (at DefaultLayout.js:158)
in DefaultLayout (created by Context.Consumer)
in Connect(DefaultLayout) (created by Route)
in Route (at DefaultLayout.test.js:22)
in PersistGate (at DefaultLayout.test.js:21)
in Provider (at DefaultLayout.test.js:20)
in Router (created by BrowserRouter)
in BrowserRouter (at DefaultLayout.test.js:19)
我已经尝试过以route.component
的方式嵌套<Component />
的方法,但是当它与其他组件通信时,这种方法有点复杂。显然,我曾尝试将组件嵌套在箭头函数() => (route.component)
中,但仍然收到警告。
我尝试过的方法(“复杂”方法):
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) => {
return this.loggedIn
? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
}}
/>
)
我希望呈现一个<Route />
,它接收组件[{component: Dashboard}]
,而不会发出警告。
答案 0 :(得分:1)
您应使用以下组件:
<Route
key={index}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} />
)}
/>
答案 1 :(得分:0)
尝试一下
function isLoggin() {
return this.loggedIn ? true : false;
}
function PrivateRoute ({component: Component, ...rest}) {
return (
<Route
{...rest}
render={(props) => isLoggin()
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
<BrowserRouter>
<Switch>
<PrivateRoute path='/dashboard' component={Dashboard} />
</Switch>
</BrowserRouter>