【问题标题】:When and how to redirect with Apollo Client and React Router何时以及如何使用 Apollo 客户端和 React 路由器进行重定向
【发布时间】:2019-05-22 07:01:02
【问题描述】:

我使用 Apollo 创建了一个 React 组件,我目前使用渲染函数在数据加载后执行重定向,但我收到警告:Warning: Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state.

这是我的代码: https://gist.github.com/jmn/c3f7c4489cd5f759808a62b48352ce87

重定向部分:

render() {
    return (
      <Query query={Q} variables={{ cursor: this.props.match.params.id }}>
      {({ loading, error, data, fetchMore }) => {
        if (loading) return <p>Loading...</p>;
        if (error) return <p>Error :(</p>;
        if (!this.props.match.params.id) {
          this.props.history.push(
            "/post/" + data.allPosts.pageInfo.endCursor
          );
        }
        return (
          <div></div>
        )

如何在惯用的 React 代码中做到这一点并避免任何警告?

【问题讨论】:

    标签: reactjs react-router apollo


    【解决方案1】:

    看起来您正在使用 React Router v4,尽管我不太确定。正如在 React 路由器中看到的 docs

    历史是可变的

    这就是为什么调用this.props.history.push() 会导致上述错误。相反,不要改变历史道具,请考虑使用&lt;Redirect /&gt; 组件,如下所示:

    if (!this.props.match.params.id) {
       return <Redirect to={"/post/" + data.allPosts.pageInfo.endCursor}
    }
    

    有关&lt;Redirect /&gt; 的更多信息,请参阅here

    【讨论】:

    • 感谢您的回答。当我尝试这个时,我得到了这个错误:“第 65 行:期望一个赋值或函数调用,而是在 上看到一个表达式 no-unused-expressions ”
    • 我创建了一个包含条件 的函数,并在渲染函数返回语句中调用它,这很有效,谢谢。
    • 很抱歉。我在上面编辑了我的答案,因为您实际上需要返回 组件。很高兴你想通了
    猜你喜欢
    • 2022-10-25
    • 2021-05-01
    • 2015-04-17
    • 2012-04-28
    • 2018-07-23
    • 2018-12-25
    • 2014-07-21
    • 2021-03-02
    • 2019-10-11
    相关资源
    最近更新 更多