【问题标题】:React Stateful Class Component: using "this.setState" to update properties of the state, not working. No error. State doesn't changeReact Stateful Class Component:使用“this.setState”更新状态的属性,不起作用。没有错误。状态不变
【发布时间】:2020-11-14 19:41:18
【问题描述】:

我知道有几个问题可以解决这个问题,但它们对我没有帮助。我基本上有这个:

state: {
  location: 'Tahiti',
  price: ['2000'],
  day: {August}
  
}

componentDidMount() {
    const updatedprice = '1800'
    this.setState({price: updatedprice})
}

我对其他属性或多或少做了相同的事情,除了我尝试将对象设置为新状态的价格。这一直对我有用,并且正在其他地方工作。出了什么问题?有什么指点吗?

所有的组件基本上都是这个。我只是想玩修改状态。

PS 我在设置状态时做了一个 console.log on:this.setState({price: updatedprice}),它给出了 undefined,这也发生在其他属性上。 虽然,我没有错误,只是当我 console.log 状态时,它显示零差异。

【问题讨论】:

  • 您的描述似乎有点单薄。你能提供更多的上下文吗? (另外,这可能无法解决您的问题,但 price 的初始值为 Array,而更新后的值为 String。)
  • 感谢您的参与!这只是一个抽象。我没有包含我的整个代码,因为它有 20 多个属性,并且我基本上尝试使用不同的值更新几个,就像上面一样。 this.setState 都发生在 componentDidMount 内,我尝试编写一个函数来设置状态,然后在组件内调用它。无论新属性值是否相同,它总是返回该状态属性的旧值。我在设置状态时做了一个 console.log on:this.setState({price: updatedprice}),它给出了 undefined。

标签: javascript reactjs components state lifecycle


【解决方案1】:

你只是语法错误。

this.setState({price: updatedprice});

【讨论】:

  • 感谢您的收获!我不知道我为什么在这里写它,我应该复制和粘贴。在我的应用程序中它实际上是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多