React Router 导致 Redux 容器组件不必要地重新渲染

Jas*_* Xu 6 reactjs react-router redux react-redux

这是我的主要代码?App组件连接到 Redux 的商店:

class App extends Component {
  render() {
    const { requestQuantity } = this.props;
    return (
      <div>
        <Router>
          <Switch>
            <Route exact path="/" component={PostList} />
            <Route path="/login" component={Login} />
            <Route path="/topics" component={PostList} />
          </Switch>
        </Router>
        {requestQuantity > 0 && <Loading />}
      </div>
    );
  }
}

const mapStateToProps = (state, props) => {
  return {
    requestQuantity: getRequestQuantity(state)
  };
};

export default connect(mapStateToProps)(App);
Run Code Online (Sandbox Code Playgroud)

PostList 组件也连接到 Redux 的商店:

class PostList extends Component {
  componentDidMount() {
    this.props.fetchAllPosts();
  }

  render() {
    const { posts} = this.props;
    return (
      // ...
    );
  }

  //...
}

const mapStateToProps = (state, props) => {
  return {
    posts: getPostList(state),
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(postActions, dispatch),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(PostList);
Run Code Online (Sandbox Code Playgroud)

this.props.fetchAllPosts()被调用时,requestQuantity全局状态中的 将从 0 变为 1(请求开始)然后变为 0(请求结束)。所以App会重新渲染两次。但是,每次重新渲染App也会导致PostList重新渲染,这是我不期望的,因为PostList仅取决于posts全局状态,posts并且在这些两次重新渲染中不会改变。

我检查了 React Router 的源代码,发现它Route的 componentWillReceiveProps 将始终调用 setState,它设置了一个新match对象:

  componentWillReceiveProps(nextProps, nextContext) {
    warning(
      !(nextProps.location && !this.props.location),
      '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'
    )

    warning(
      !(!nextProps.location && this.props.location),
      '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.'
    )

    //the official always set a new match object ignoring whether the nextProps change or not
    this.setState({
      match: this.computeMatch(nextProps, nextContext.router)
    })
  }
Run Code Online (Sandbox Code Playgroud)

这是match传递给PostListRedux 的浅比较失败并发生重新渲染的新道具。希望之前 React Router 的团队可以做一些简单的逻辑setState,比如使用 ( ===) 比较 nextProps 和 this.props 中的每个 prop,如果没有变化,则跳过setState。不幸的是?他们认为这没什么大不了的并结束了我的问题。

现在我的解决方案是创建一个 HOC:

// connectRoute.js
export default function connectRoute(WrappedComponent) {
  return class extends React.Component {
    shouldComponentUpdate(nextProps) {
      return nextProps.location !== this.props.location;
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

然后用于connectRoute包装在 中使用的容器Route

const PostListWrapper = connectRoute(PostList);
const LoginWrapper = connectRoute(Login);

class App extends Component {
  render() {
    const { requestQuantity } = this.props;
    return (
      <div>
        <Router>
          <Switch>
            <Route exact path="/" component={PostListWrapper} />
            <Route path="/login" component={LoginWrapper} />
            <Route path="/topics" component={PostListWrapper} />
          </Switch>
        </Router>
        {requestQuantity > 0 && <Loading />}
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

此外,当 React Router 与 Mobx 一起使用时,这个问题也很容易遇到。

希望有人能提供更好的解决方案。一个很长的问题。谢谢你的耐心。