react在url相同但参数不同的页面间跳转时如何根据参数去修改页面

我是把更新方法写在componentWillReceiveProps里,但是setState是异步的,页面没有及时更新,请问有什么方法解决吗

state = {
    type: '页面2'
}
componentWillReceiveProps(nextProps:any) {
    this.setState({
      type:'页面1'
    })
  }
 render() {
  return (
    <div>{this.state.type}</div>
  )
 }
阅读 3.4k
2 个回答
constructor(props) {
  super(props);
  var type = "页面1"
  this.state = {type};
}

1、建议看下文档:https://zh-hans.reactjs.org/d...
2、更新数据不要用 componentWillReceiveProps 这个生命周期已经废弃了,建议使用 componentDidUpdate
3、应该这么更新数据:

componentDidUpdate(prevProps) {
  // 典型用法(不要忘记比较 props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题