我正在 React 中制作一个待办事项列表。这些项目存储在应用程序状态的对象中。当用户选中该框时,我可以更新状态,但不显示更新后的状态。我知道状态更改并不总是立即更新组件,因此我尝试传递 render()
函数作为 setState()
的回调函数,但我收到一条错误消息 Invalid argument passed as callback. Expected a function. Instead received: [object Object]
。我还尝试添加 componentDidUpdate()
函数,但使用该方法没有取得任何成功,因为我不明白它是如何触发的。如何更新状态并立即在页面上显示更新后的状态?
到目前为止,我拥有的这个函数是在选中/取消选中复选框时触发的。
constructor(props) {
super(props);
this.state = {
isLoading: null,
isDeleting: null,
list: null,
title: "",
term: "",
content: []
};
}
async componentDidMount() {
try {
const list = await this.getList();
const { title, content } = list;
this.setState({
list,
title,
content
});
} catch (e) {
alert(e);
}
}
checkedChange = async event => {
let todos = Object.assign({}, this.state.content);
let key = event.target.attributes[0].value;
if(event.target.checked) {
todos[key] = true;
this.setState({todos});
}
else {
todos[key] = false;
this.setState({todos});
}
};
最佳答案
语法 this.setState({todos})
与编写 this.setState({todos: todos})
等效。所以你没有更新 this.state.content
我怀疑这就是你想要做的。因此,请尝试 this.setState({content: todos})
。
编辑:我强烈建议您安装并使用 Chrome React developer tools 。它将作为控制台、检查器等旁边的选项卡显示在您的开发托盘中。它对于调试和可视化组件中发生的情况非常有用。
关于javascript - 在 React 中显示更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138226/