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

Javascript Push方法将数组转换为组件状态下的数字,javascript,arrays,reactjs,state,lifecycle,Javascript,Arrays,Reactjs,State,Lifecycle,我有一个存储在组件状态中的数字数组,我正在使用componentDidMount方法中的计时器内的setState推送另一个数字,以查看它在屏幕上的变化。但当计时器完成时,现有数组将被我在push方法中作为参数传递的数字替换,而不是将其追加到数组中 class Foo extends React.Component { constructor(props){ super(props); this.state = { array :

我有一个存储在组件状态中的数字数组,我正在使用
componentDidMount
方法中的计时器内的
setState
推送另一个数字,以查看它在屏幕上的变化。但当计时器完成时,现有数组将被我在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'));
类Foo扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
数组:[1,2,3,4,5]
}
}
componentDidMount(){
setTimeout(()=>this.setState(prevState=>({
数组:prevState.array.push(6),
})), 5000)
}
render(){
const newArray=this.state.array;
返回(
{newArray}
);
}
}
ReactDOM.render(,document.getElementById('root'));

我可以使用spread运算符而不是push使其工作,但现在我想知道为什么push不能工作。

Array.prototype.push
在推送项目后返回数组的长度,这就是为什么会得到意外结果,您应该使用
Array.prototype.concat
,它在添加元素时重新运行一个新数组

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

Array.prototype.push
推送项后返回数组的长度,这就是为什么会得到意外结果的原因,您应该使用
Array.prototype.concat
而不是在添加元素后重新推送新数组

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

还可以计算非数组值
prevState.array.concat(6)
返回相同的结果,不需要额外的数组来包装
6
。您可能想签出,也可以指定非数组值
prevState.array.concat(6)
返回相同的结果,不需要额外的数组来包装
6
。你可能想退房