Push方法在组件状态下将数组转换为数字

问题描述 投票:0回答:1

我在组件的状态下存储了一个数字数组,我正在尝试在setState方法的计时器内部使用componentDidMount推送另一个数字,以查看其在屏幕上的变化。但是,当计时器结束时,现有数组将替换为我在push方法中作为参数传递的数字,而不是将其附加到数组中。

class Foo extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            array : [1,2,3,4,5]
        }
    }

    componentDidMount(){
        setTimeout(()=>this.setState(prevState=>({
            array: prevState.array.push(6),
        })), 5000)
    }

    render(){
        const newArray = this.state.array;
        return(
            <div>{newArray}</div>
        );
    }
}

ReactDOM.render(<Foo />,document.getElementById('root'));

我可以使用传播运算符而不是push使其工作,但现在我想知道为什么它也不能与push一起工作。

javascript arrays reactjs state lifecycle
1个回答
2
投票

[Array.prototype.push返回项目后推入数组的长度,这就是为什么您得到意外结果的原因,应该使用Array.prototype.concat代替,当添加元素时会重新调整新的数组]

  setTimeout(()=>this.setState(prevState=>({
        array: prevState.array.concat([6]),
  })), 5000)
© www.soinside.com 2019 - 2024. All rights reserved.