我是 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 }
我已经阅读了很多关于如何使用道具传递历史对象以及如何使用组件的信息,但我看不出这些方法在这里如何工作。我的上下文提供程序位于树的顶部,因此它不是路由器的子节点,因此我无法传递道具。它也不是标准组件,所以我不能只插入一个组件,除非我误解了某些东西(这很有可能)。
Edit: Looks like the way to go is withRouter, but how to export my AuthProvider in the code above so that history.push is available in my login function? As you can see I'm exporting multiple components wrapped in {} so can you wrap one of these in a HOC and do you have to explicitly pass history in or is it always available inside the component that's being wrapped?