tl;dr -- 我想在组件状态发生变化时触发回调
我有一个组件可以改变 this.props.items
并在每次改变时触发 this.props.onChange
。我目前正在做这样的事情:
removeItem(ix) {
const items = this.state.items.slice();
items.splice(ix, 1);
this.setState({ items });
this.triggerOnChange();
}
我想知道是否可以删除对 triggerOnChange
的手动调用,而是在 this.state.items
更新时执行此操作
最佳答案
this.setState
接受两个参数,第一个是对象(状态),第二个是回调(可选)
this.setState({...}, function(){
console.log('changed')
})
来自 Spec
The second parameter is an optional callback function that will be executed once setState is completed and the component is re-rendered
关于javascript - react 中是否有状态突变观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848482/