gpt4 book ai didi

javascript - 如何使用对象而不是组件/函数从 react-router-dom 渲染

转载 作者:行者123 更新时间:2023-11-30 19:35:22 26 4
gpt4 key购买 nike

我有一个对象列表,其中有一个 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}] ,没有任何警告。

最佳答案

您应该使用如下组件:

<Route
key={index}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} />
)}
/>

关于javascript - 如何使用对象而不是组件/函数从 react-router-dom 渲染 <Route/>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998665/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com