【问题标题】:Redirect React Router from Context Provider从上下文提供者重定向 React 路由器
【发布时间】: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


【解决方案1】:

使用 withRouter, 像这样获取历史记录。

 const AuthButton = withRouter( ({ history }) =>history.push("/"));

试试这个:

    import { Route } from "react-router-dom";

  class AuthProvider extends React.Component {
    yourFunction = () => {
      doSomeAsyncAction(() =>
        this.props.history.push('/dashboard')
      )
    }

    render() {
      return (
        <div>
          <Form onSubmit={ this.yourFunction } />
        </div>
      )
    }
  }

  export default withRouter(AuthProvider);

最好的解释可以在这里找到:Programmatically navigate using react router

【讨论】:

  • 在我标记为正确之前检查一下,我如何导出包装在 withProvider 中的 AuthProvider,以便我可以在其中使用历史记录。我将编辑我的问题以反映这一点。
  • 不,当我尝试将 withRouter 与我的 AuthProvider 一起使用时,我收到错误消息 - “您不应在 之外使用 或 withRouter()”
  • 好的,当我交换 AuthProvider 和 BrowserRouter 标签的嵌套以便 AuthProvider 在 BrowserRouter 内时,它起作用了。
  • 好的,我已将您的答案标记为正确,因为它使我得到了正确的答案,但在我的应用程序中,使用上下文提供程序的全部意义在于我的表单包含对登录的调用函数不能在提供者本身中,它在上下文消费者内部的组件树中。困难在于从提供程序内部访问路由器,这要归功于 withRouter 并将提供程序嵌套在路由器组件中。
猜你喜欢
  • 2015-04-16
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2021-02-04
  • 1970-01-01
  • 2010-09-19
  • 2019-07-16
相关资源
最近更新 更多