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

时间:2017-01-25 06:59:30

标签: reactjs redux react-router react-redux

我有路由/ 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状态以及组件状态将更新,但组件不会在显示新区域数据的情况下重新呈现。

2 个答案:

答案 0 :(得分:1)

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

然后

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

答案 1 :(得分:0)

您应该在setState()中添加componentWillReceiveProps

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

here就是文件。

相关问题