如何解决如何在ReactJS状态数组中添加更多元素?
this.state.counter.map
不是我需要添加对象并将其映射到计数器的函数
我需要创建并推送到计数器数组,然后映射到计数器并在此浏览器中显示如何执行此操作?
import React,{ Component } from 'react';
import Counter from './counter';
class Counters extends Component {
state = {
counter: [
{value:0,id:1},{value:0,id:2},id:3},id:4},]
};
// function for create new array and map to him for delete one of counter in browser
DeleteButten = counterId => {
const counter = this.state.counter.filter(c =>c.id !== counterId);
this.setState({counter});
};
// this function for push new object to array and show in browser
AddCounter = () => {
const counter = this.state.counter.push({value:0,id:5});
console.log(this.state.counter);
this.setState({counter}); // error this.state.counter.map is not a function i need help to add object and map to counter
};
render() {
return (
<div>
{this.state.counter.map(counter => (
<Counter
key={counter.id}
onDelete{this.DeleteButten}
value={counter.value}
id={counter.id} selected={true}
/>
)}
<button onClick={this.AddCounter} className='btn btn-outline-info btn-sm m-2'> ADD result</button>
</div>
);
}
}
export default Counters;
解决方法
如果只想向数组添加元素,则代码如下:
this.setState({counter:...this.state.counter,new_count})
new_count
是您要推送的内容
在您的代码中此行:
const counter = this.state.counter.push({value:0,id:5});
您正在直接更改状态数组,这在React中是不允许的。
您可以(浅)克隆阵列并对其进行修改:
// This does a shallow clone of the array.
const newCounter = [...this.state.counter];
// Modify the new array.
newCounter.push({ value: 0,id: 5 });
// Set the new array back to the state using setState.
this.setState({ counter: newCounter });
或者,您可以使用较短的语法来添加新元素并同时创建新数组:
// Append a new element to the new cloned array.
this.setState({ counter: [...this.state.counter,{ value: 0,id: 5 });
// Or you can put the element at the front if you like :)
this.setState({ counter: [{ value: 0,id: 5 },...this.state.counter]);
三点([...array]
)语法称为 spread ,可与数组和对象一起使用,以方便地克隆或重建新的数组或对象! Check out the MDN docs about it here.
还有一点需要改进的地方是,上面的代码大部分都可以工作,但是请注意,React setState
是异步的,有可能出现竞争状况
例如,假设您在同一事件循环中多次调用AddCounter
方法,则后面的结果可能会覆盖前面的结果。
因此,如果您要设置一些取决于当前状态的内容,建议使用回调语法:
this.setState(state => { counter: [...state.counter,id: 5 }] });
See more details and examples of the async nature of setState in React docs.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。