首页 > 解决方案 > 每次调用 mapStateToProps 时,与Router 反应都会为匹配创建一个新对象

问题描述

不确定其他人之前是否遇到过这个问题:

我正在使用:“react-redux”:“5.0.7”,“react-router”:“4.2.0”,“react-router-dom”:“4.2.2”

所以我有一个这样的组件,

shouldComponentUpdate = (nextProps) => {
    // shallow compare each prop and see which one is changed
    console.log(nextProps.history === this.props.history) // true, good
    console.log(nextProps.location === this.props.location) // true, good
    console.log(nextProps.match === this.props.match) // false, what? althought the value inside match is the same? why match is a new object/reference every time?
}

const mapStateToProps = (state, ownProps) => {
  nothing special here, just merge state and ownProps. (Router location/match/history is in ownProps, withRouter inject them in i think)
  at the end of this function i just return the merge of {state, ownProps}
  same issue exists even without my own mapStateToProps
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MyComponent))

每次发生状态变化时,都会调用 mapStateToProps。withRouter 将 location/match/history 注入到 ownProps 中。但是由于某种原因,每次调用 mapStateToProps 时,“匹配”都是一个新对象,因此会导致不必要的重新渲染。

标签: reactjsreact-routerreact-router-domreact-router-redux

解决方案


推荐阅读