使用 React router v4 的对象作为 React 子对象无效
Objects are not valid as a React child using react router v4
这是我的包装器组件,也就是 auth 组件,只允许授权用户访问。
Auth.js
render() {
const { Component: component, ...rest } = this.props;
return (
<Route>
{rest}
render={props =>
this.isAuth === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login"
}}
/>
)
}
</Route>
);
}
有什么问题吗?这是我的路线声明
Index.js
render(
<BrowserRouter>
<div className="App">
<Switch>
<Route path="/login" component={Login} />
<Auth path="/dashboard" component={Dashboard} />
</Switch>
</div>
</BrowserRouter>,
document.getElementById("root")
);
我做了一个演示来重现这里的问题
https://codesandbox.io/s/5xm202p1j4
我在官方文档中使用了相同的概念,https://reacttraining.com/react-router/web/example/auth-workflow 只是没有将 auth.js 设为纯函数,而是将其设为 class 基础容器,以便我可以调用api 或者检查我的本地存储中是否存在用户的令牌,到底是什么问题?
你是想做这样的事情吗:
render() {
const { Component: component, ...rest } = this.props;
return (
<Route
{...rest}
render={props =>
this.isAuth === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login"
}}
/>
)
}
/>
);
}
通过在 <Route>
标签中加入 rest
和 render
,这样 rest
就会传递给 <Route>
?
这是我的包装器组件,也就是 auth 组件,只允许授权用户访问。
Auth.js
render() {
const { Component: component, ...rest } = this.props;
return (
<Route>
{rest}
render={props =>
this.isAuth === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login"
}}
/>
)
}
</Route>
);
}
有什么问题吗?这是我的路线声明
Index.js
render(
<BrowserRouter>
<div className="App">
<Switch>
<Route path="/login" component={Login} />
<Auth path="/dashboard" component={Dashboard} />
</Switch>
</div>
</BrowserRouter>,
document.getElementById("root")
);
我做了一个演示来重现这里的问题 https://codesandbox.io/s/5xm202p1j4
我在官方文档中使用了相同的概念,https://reacttraining.com/react-router/web/example/auth-workflow 只是没有将 auth.js 设为纯函数,而是将其设为 class 基础容器,以便我可以调用api 或者检查我的本地存储中是否存在用户的令牌,到底是什么问题?
你是想做这样的事情吗:
render() {
const { Component: component, ...rest } = this.props;
return (
<Route
{...rest}
render={props =>
this.isAuth === true ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login"
}}
/>
)
}
/>
);
}
通过在 <Route>
标签中加入 rest
和 render
,这样 rest
就会传递给 <Route>
?