【问题标题】:Can't use history.push to async route, React JS不能使用 history.push 到异步路由,React JS
【发布时间】:2019-07-13 23:20:39
【问题描述】:

我正在使用这个包https://github.com/SimpleContacts/react-router-async-routes

<Route
    async
    path={`${match.url}app`}
    render={async () => {
      try {
        Promise.all([await Axios.get('/api/loggedin')]).then((userData) => {
          this.props.setUser(userData[0].data);
        });
        return <MainApp />
      } catch (err) {
        return <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />
      }
    }}
  /> //history.push not working on this one.
<Route path={`${match.url}somepage`} component={SomeComp} /> // history.push works

当我使用 React Router 的 history.push 到自定义异步路由 /app 时,url 发生变化,redux 路由发生变化,但未加载 App-component。它正在一条“正常”的路线上工作。

我无法确定问题出在哪里。

有什么想法吗?

【问题讨论】:

  • 你有嵌套BrowserRouter 吗?我有类似的问题..

标签: reactjs react-router


【解决方案1】:

App Route 渲染道具回调方法中的 await 语句位于不正确的位置。在返回组件之前,它不会等待Promise.all 解决。您也可以在没有 Promise.all 的情况下编写代码,如下所示

<Route
    async
    path={`${match.url}app`}
    render={async () => {
      try {
        const userData = await Axios.get('/api/loggedin')
        this.props.setUser(userData.data);
        return <MainApp />
      } catch (err) {
        return <Redirect to={{ pathname: '/login', state: { from: this.props.location } }} />
      }
    }}
  /> //history.push not working on this one.
<Route path={`${match.url}somepage`} component={SomeComp} />

DEMO

PS 确保您的 API 为您提供正确的响应 降落在捕获块中

【讨论】:

  • 你能举个例子,说明你在其他路径,然后使用 history.push('/app') 吗?另外,Promise.all 的原因是因为在实际代码中我有更多的调用。
  • 如果您希望使用 Promise.all,请在 promise.all 块之外使用 await。当然我会在一段时间内进行演示
  • 请做。等待只是一个错误的输入。这不是问题。
  • @Joe 在答案中的同一链接更新了演示。请检查
【解决方案2】:

等待 Promise.all 你应该没问题,但正如其他人之前所说,看起来你根本不需要 Promise.all(你在该数组中只有一个函数,所以你可以完全放弃它。

...
try {
  await Promise.all(...

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 2019-05-30
    • 2022-08-23
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多