我似乎无法让 setState 更改(变异)来自方法/函数的参数或参数的值。至少,第一次通话时它不起作用。在值更改之前我必须调用 setState 两次。
import React from 'react'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
testItem: 'originalValue'
}
}
updateState(input) {
this.setState({
testItem: input
},
console.log(this.state.testItem) // displays 'originalValue' instead of 'newValue!', at least on the first call
)
}
render() {
return (
<button onClick={() => this.updateState('newValue!')}>
Change State
</button>
)
}
}
export default App
“testItem”的状态应从“originalValue”更改为“newValue!” (取自方法“updateState(input)”中的参数“input”)单击按钮时,但第一次单击时它不会更改(即使在 setState 中使用回调时也是如此)。仅当我第二次单击该按钮时它才会改变。这是为什么?
最佳答案
现在,console.log
会立即以当前状态调用,这是您设置的初始状态,因为 setState
是异步的(即状态不会立即更新)与最新的变化)。
因此,我们需要通过将 console.log
包装在函数中来推迟其调用。我们这样做是为了稍后可以通过 setState
调用它,而不是每次调用 setState
为此,您需要传递一个回调函数,该函数将在执行 setState
后执行。
this.setState({ testItem: input}, () => console.log(this.state))
关于javascript - ReactJS setState 不适用于方法/函数中的参数/参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58255317/