javascript - 使用 immutability-helper 在 if else 语句中调用时反应 this.state 未正确更新
问题描述
我正在尝试创建一个简单的水平标签栏组件。如果用户单击选项卡,则容器会执行一些逻辑。
通过this.state在容器中跟踪选项卡状态。容器的道具之一是一个名为“选项”的数组。长度决定了标签栏中的标签数量。
constructor(props){
super(props)
var arrayWithTabs = []
var isSelected;
this.props.options.map((option, i) => {
if (option == this.props.selected){
isSelected = true
} else {
isSelected = false
}
var tabObject = {
optionName: option,
isSelected: isSelected
}
arrayWithTabs.push(tabObject)
})
this.state = {
options: arrayWithTabs,
}
每当用户单击 handleClick 时,都会触发:
updateState = (index,isSelected) => {
this.setState((prevState) => {
return update(prevState.options,{
[index]: {
isSelected:{$set: isSelected}
}
})
})
}
handleClick(e) {
this.state.options.map((option, i) => {
const isSelected = option.optionName == e.target.id;
this.updateState(i, isSelected);
})
}
componentDidUpdate(){
console.log(this.state.options)
}
为了处理我读到的 setState 的异步行为,你永远不应该直接从 this.state 中读取,而是在 setState 中创建一个函数来接收 prevState。
但是,当单击任何选项卡时, componetDidUpdate() 会返回以下内容:
[{optionName: "Tab1", isSelected: false}
{optionName: "Tab2", isSelected: false}]
解决方案
您可以使用回调来确保setState
已完成,例如:
addNewTabs(newOptions) {
this.setState({ options:newOptions }, () => {
console.log("Finished updating state:", this.state);
// Do something with the updated state here...
});
}
尝试将您的代码重组为以下内容:
handleClick(e) {
var updatedState;
this.state.options.map((option, i) => {
const isSelected = option.optionName == e.target.id;
updatedState = update(this.state.options, {
[i]: {$set:{optionName: option.optionName, isSelected:isSelected}}
});
});
this.setState({ options:updatedState }, () => {
console.log(updatedState);
});
}
推荐阅读
- java - 如何配置测试套件始终将常量注入到所有类实例的@value私有字段中
- c# - 将文件上传到 WindowsForms C# 中的 Rest API
- java - 带有实体列表的 Android Room IN 条件
- java - 另一个使用 Spring 的 JUNIT 测试——Autowired not working 问题
- javascript - 我可以按 id 或按类选择多个 html 元素吗?
- c# - 在 ASP.NET MVC5 中传递给控制器时,DateTime 字段为空
- javascript - 从高到低排列数组
- google-cloud-dataflow - Beam SQL 未触发
- php - 如何在 laravel 中以具有路由 ID 的用户身份进行身份验证
- docker - 无法从 docker 容器内访问主机上运行的某些服务