【问题标题】:How to update state that is passed through react router link如何更新通过反应路由器链接传递的状态
【发布时间】:2021-09-20 14:59:03
【问题描述】:

所以我正在使用 react-router,并且在我通过从 page1 到 page2 的链接发送一些状态之后

<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;        
}

有什么建议吗?

【问题讨论】:

  • 您是否登录this.props.location.state 以确保您获得状态?你绝对应该使用setState
  • 是的,我正在接收状态,我只是不知道如何更新它@Ace
  • 你能说明你是如何使用setState的吗?
  • this.setState({featured: !this.props.location.state.resort.featured}) @Ace

标签: javascript reactjs react-router state routerlink


【解决方案1】:

永远不要直接改变this.state

试试这样:

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

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

【讨论】:

  • 在componentdidmount中调用set state不是坏习惯吗?
  • 很好的答案!在我发布我的之前没有看到这个。
  • @fortunee 我猜我只早了几秒钟:v
  • @AbdurahmanHijazi 不,根据 React 文档,从 componentDidMount() 中调用 setState() 是完全可以的
  • 有道理谢谢@fortunee 和 Xenon
【解决方案2】:

考虑使用componentDidMount 生命周期挂钩并使用setState 将这些值设置为组件state,如下所示

这样

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

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

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 2021-04-13
    • 2017-08-10
    • 2018-12-14
    • 2019-07-07
    • 2021-05-24
    • 2021-07-07
    • 1970-01-01
    相关资源
    最近更新 更多