我想在react状态下为数组添加一个新值,但是我一直遇到错误,有人可以指导我解决这个问题吗?
class App extends Component {
constructor(props) {
super(props);
this.state = {
Items: [
{w:1, b:8, name: 'banana'},
{w:7, b:3, name:'apple'},
{w:3, b:5, name:'kiwi'},
{w:6, b:3, name:'strawberry'},
{w:5, b:1, name:'orange'}]
};
}
addItem(weight, benefit, itemName){
this.setState(prevState => ({
Items: [...prevState.Items, {w:weight, b:benefit, name: itemName}]
}))
}
答案 0 :(得分:0)
您必须绑定addItem
函数才能使用“this”而不会出错。
有两种方式:
1 /词法绑定:(使用“=>”)
addItem = (weight, benefit, itemName) => {
this.setState(prevState => ({
Items: [...prevState.Items, {w:weight, b:benefit, name: itemName}]
}))
}
2 /在构造函数中绑定:
constructor(props) {
super(props);
this.state = {
Items: [
{w:1, b:8, name: 'banana'},
{w:7, b:3, name:'apple'},
{w:3, b:5, name:'kiwi'},
{w:6, b:3, name:'strawberry'},
{w:5, b:1, name:'orange'}]
};
this.addItem = this.addItem.bind(this);
}