首页 文章

React,redux组件不会在路由更改时更新

提问于
浏览
2

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

我尝试adding in a key<Link/> 被点击以更改路由以触发更新,但这不起作用 .

跟着troubleshooting guide for react-redux并认为我可能会以某种方式改变状态?

也许我想以错误的方式改变路线?

我挂钩到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显示状态确实返回新区域,但不更新组件 .

Reducer

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

Root Reducer

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

因此,props和redux状态以及组件状态将更新,但组件不会在显示新区域数据的情况下重新呈现 .

2 回答

  • 0
    import {withRouter} from 'react-router-dom'
    

    然后

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

    您应该在 componentWillReceiveProps 中添加 setState() .

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

    here是文件 .

相关问题