我尝试使用react router dom v4在私有路由中呈现两个组件。这可以使用普通路由,但在使用自定义路由时似乎不是这种情况。我收到以下错误: “警告:React.createElement:类型无效 - 期望一个字符串(对于内置组件)或类/函数(对于复合组件)但得到:undefined。您可能忘记从其定义的文件中导出组件,或者您可能混淆了默认导入和命名导入。 “
自定义路线(经过验证)return (
<Route
{...rest}
render={props =>
this.currentUser()
? <Component currentUser={this.currentUser} {...props} />
: <Redirect
to={{
pathname: '/auth/login',
state: { from: props.location }
}}
/>
}
/>
)
然后在我的路线我想要这样的东西
return (
<div>
<Switch location={isModal ? this.prevLocation : location}>
<Authenticated path="/" exact component={Main} />
<Route path="/auth/register" exact component={Register} />
<Route path="/auth/login" exact component={Login} />
<Authenticated
path="/clients/:id/edit"
render={(props) => ( // Not working as expected. Works fine using Route instead of Authenticated
<div>
<Main />
<ClientEdit />
</div>
)}
/>
</Switch>
{isModal ?
<Authenticated
path='/clients/new'
component={ClientNew}
/>
: null}
{isModal ?
<Authenticated
path='/clients/:id/edit'
component={ClientEdit}
/>
: null}
</div>
);
答案 0 :(得分:1)
在您的protectedRoute组件中,您没有收到或使用您在该行发送的render
道具:
render={(props) => (
<div>
<Main />
<ClientEdit />
</div>
)}
而不是使用渲染发送component
道具中的组件,如:
component={(props) => (
<div>
<Main />
<ClientEdit />
</div>
)}
同时检查路由器的文档,查看何时使用component
道具以及何时使用render
道具。如果你可以改变你的protectedRoute
来处理这两个问题会好得多。
答案 1 :(得分:1)
我来晚了,但是对于仍然需要此功能的任何人,我发现这对我来说很有效。
export function PrivateRoute({ component: Component = null, render: Render = null, ...rest }) {
const authService = new AuthService();
return (
<Route
{...rest}
render={props =>
authService.isAuthenticated ? (
Render ? (
Render(props)
) : Component ? (
<Component {...props} />
) : null
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
);
}
在我的路线中,我像这样使用它:
<PrivateRoute
path="/some-route/edit"
render={props => <MyComponent {...props} isAwesome={true} />} />
答案 2 :(得分:0)
我认为您需要创建一个返回的自定义组件:
moduleId: module.id
然后导入它并在经过身份验证的组件中使用它,如下所示:
return(
<div>
<Main />
<ClientEdit />
</div>)
编辑:如果提供,您还可以在Authenticated组件中处理渲染道具:
<Authenticated
path="/clients/:id/edit"
component={CustomComponent}
/>