【问题标题】:React, redux component does not update on route changeReact,redux 组件不会在路由更改时更新
【发布时间】:2017-06-10 06:17:08
【问题描述】:

我有路由/zone/:id,当从/zone/123点击到/zone/789时,我可以成功调度一个动作来获取新的状态,但是组件没有渲染来显示新的数据。

我尝试adding in a key<Link/> 被点击以更改路由以触发更新,但没有奏效。

关注 react-redux 的 troubleshooting guide 并认为我可能会以某种方式改变状态?

也许我试图以错误的方式更改路线?

我连接到 ComponentWillReceiveProps 并检查 params.id 是否已更改,如果已更改,我会发出 fetchZone 操作以检索新区域。

Zone.js

class Zone extends Component{
  constructor(){
    super()

    this.state = {
      zone: {}
    }
  }

  componentDidMount(){
    this.props.fetchZone(this.props.params.id)
  }

  componentDidUpdate(prevProps){
    if (prevProps.zone !== this.props.zone){
      this.setState({zone: this.props.zone})
    }  
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.params.id !== this.props.params.id){
      this.props.fetchZone(nextProps.params.id)
    }
  }

 render(){
   ...
 }

 function mapStateToProps(state){
  return {
      zone: state.zones.zone,
      coordinates: state.zones.coordinates
    }
}

export default connect(mapStateToProps, {fetchZone, getCoordinates})(Zone)

Using react-logger 表示状态确实返回了新区域,但不更新组件。

减速器

case FETCH_ZONE:
  return { ...state, zone: action.payload.data.result}

Root Reducer

const rootReducer = combineReducers({
  zones: ZonesReducer,
  form: formReducer
});

因此 props 和 redux 状态以及组件状态将更新,但组件不会重新渲染并显示新的区域数据。

【问题讨论】:

    标签: reactjs redux react-router react-redux


    【解决方案1】:
    import {withRouter} from 'react-router-dom'
    

    然后

    withRouter(connect(mapStateToProps, {fetchZone, getCoordinates})(Zone))
    

    【讨论】:

      【解决方案2】:

      您应该在componentWillReceiveProps 中添加setState()

      componentWillReceiveProps(nextProps){
          if(nextProps.params.id !== this.props.params.id){
            this.props.fetchZone(nextProps.params.id);
            this.setState(...) // setState here
          }
        }
      

      here 是文档。

      【讨论】:

      • 在使用 Redux 时使用 setState 是不是很糟糕?我认为 Redux 应该处理所有状态。如果我误解了,请纠正我。
      • @Kunok redux.js.org/docs/faq/… 你可以查看这个常见问题解答
      • 哦,我明白了,这很有道理!
      • 当我在setStatecomponentWillReceiveProps 它仍然没有更新组件。我加了if (nextProps.zone !== this.props.zone){ this.setState({ zone: nextProps.zone}) }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2021-11-15
      • 2018-09-04
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多