首页 > 解决方案 > 使用 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}]

标签: javascriptreactjstypescript

解决方案


您可以使用回调来确保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);
  });
}

推荐阅读