如何更新通过react路由器链接传递的状态

5sxhfpxr  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(220)

所以我使用react路由器,在我发送了一些状态和从第1页到第2页的链接之后

<Link
  to={{
    pathname: `/dashboard/edit/${resort.id}`,
    state: { resort: resort },
  }}
  style={{ textDecoration: 'none', color: 'black' }}
>
  <i
    className="fas fa-edit db-icon"
    style={{ background: 'rgb(12, 177, 12)', color: 'black' }}
  ></i>
</Link>;

当我进入第2页时,如何更新此状态,我已尝试使用 this.setState ,但这不起作用,我尝试过像下面这样分解发送过来的状态,但也不起作用

constructor() {
  super();
  this.state = {
    title,
    price,
    desc,
    img,
    smoking,
    guests,
    featured,
  } = this.props.location.state.resort;        
}

有什么建议吗?

a0zr77ik

a0zr77ik1#

永不变异 this.state 直接地
试着这样做:

constructor() {
  super();
  this.state = { resort: {} };      
}

componentDidMount = () => {
  this.setState({resort: this.props.location.state.resort});
}
zaqlnxep

zaqlnxep2#

考虑使用 componentDidMount 生命周期挂钩与使用 setState 将这些值设置为组件 state 这样地
这样地

constructor() {
  super();
  this.state = {
    resort: {}
  }
}

compoonentDidMount() {
  this.setState({ resort: this.props.location.state.resort })
}

相关问题