当我在代码中调用 this.setState 时,它似乎什么也没做
this.setState({array:pre.array},()=>{console.log("setState")})
我什至看不到回调函数的日志,这是我的代码
class Watch extends React.Component{
constructor(pre) {
super(pre);
this.state = { color: "green" }
this.setState(() => {
return {array:newarray}
}, console.log("setState works"))
p.s:我尝试将setState
放入onClick
函数中,在componentDidMount(),componentDidUpdate()
中仍然无法正常工作,没有错误
最佳答案
似乎在使用setState回调系统时,第一个参数(updater)也需要采用函数的形式。所以你可以尝试这样的事情:
onEditText=(value)=>{
this.setState((state, props)=>{
return {text: value}
}, this.onTextEdited);
}
onTextEdited=()=>{
//this will be printed with the updated value
console.log('onTextEdited', this.state.text)
}
看看这是否有帮助。
关于javascript - React setState 不起作用,它的回调也不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418648/