【发布时间】:2018-12-30 20:29:09
【问题描述】:
我是 React Router 的新手,并尝试使用新的 Conext API 从提供程序内部进行重定向。基本上我的提供者看起来像这样。
/* AuthContext.js */
class AuthProvider extends React.Component {
state = { isLoggedIn: false }
constructor() {
super()
this.login = this.login.bind(this)
this.logout = this.logout.bind(this)
}
login() {
this.setState({ isLoggedIn: true })
// Need to redirect to Dashboard Here
}
logout() {
this.setState({ isLoggedIn: false })
}
render() {
return (
<AuthContext.Provider
value={{
isLoggedIn: this.state.isLoggedIn,
login: this.login,
logout: this.logout
}}
>
{this.props.children}
</AuthContext.Provider>
)
}
}
const AuthConsumer = AuthContext.Consumer
export { AuthProvider, AuthConsumer }
我已经阅读了很多关于如何使用 props 传递历史对象以及如何使用组件的信息,但我看不出这些方法在这里如何工作。我的上下文提供程序位于树的顶部,因此它不是路由器的子节点,因此我无法传递道具。它也不是标准组件,所以我不能只插入一个组件,除非我误解了某些东西(这很有可能)。
编辑:看起来要走的路是withRouter,但是如何在上面的代码中导出我的AuthProvider,以便在我的登录功能中可以使用history.push?如您所见,我正在导出包装在 {} 中的多个组件,那么您可以将其中一个组件包装在 HOC 中吗?您是否必须显式传入历史记录,或者它是否始终在被包装的组件中可用?
【问题讨论】:
-
你尝试过使用历史 -> this.props.history.push("/dashboard");
-
AuthProvider 没有 props.history,除非你知道我可以将 Router 历史对象添加到 props 的方法吗?
-
使用 withRouter 之类的来获取历史记录。 const AuthButton = withRouter( ({ history }) =>history.push("/"));
-
啊,好的,只需阅读 withRouter 文档,它说它可以访问“历史对象的属性和最近的
的匹配项”,所以看起来这对我有用情况,但我猜是因为它是 的祖父母,它不会在“匹配”属性中得到任何东西。我会进一步阅读它。如果您将其添加为答案,我会将其标记为正确。非常感谢。
标签: reactjs react-router react-context