React使用.push通过onClick添加到数组 [英] React use .push to add to an array with onClick
问题描述
我试图将其添加到我的现有数组中,该数组称为players(这是导入到我的父母中的外部文件"players.js").
I am attempting to add to my existing array which is called players (which is an external file "players.js" that's imported into my parent).
我可以写:
players.push({
name: 'Maul',
id: 26
});
该键作为ID使用,并且名称在数组中更新.
And that works as ID is used for the key and the name is updated in the array.
但是我写
handleAddPlayer = () => {
console.log('i am working');
players.push({
name: 'Maul',
id: 26
});
};
在我的按钮上
<div>
<h4>Add A Player</h4>
<input />
<button onClick={this.handleAddPlayer}>Press to Add Player</button>
</div>
我的状态如下:
this.state = {
id: players.id,
totalScore: 0,
countInfo: [],
evilName: '',
color: '#6E68C5',
scoreColor: '#74D8FF',
fontAwe: 'score-icon',
incrementcolor: '',
scoreNameColor: 'white',
glow: '',
buttonStyle: 'count-button-start',
players,
};
它不起作用.
从这里我有两个问题:
-
为什么当我单击按钮时它不会更新,但在没有功能之前可以工作?
why won't it update when I click the button but works before not as a function?
我想在输入中输入一个名称,并生成一个添加到我的数组players.js中的唯一键
I would like to put a name into the input and generate a unique key that's added into my array, players.js
我尝试了级联,但没有成功.
I've tried concatenate and had not a lot of success.
推荐答案
播放器是状态对象的属性,因此您需要调用setState来更新该属性:
Players is a property on the state object, so you'll want to call setState to update the property:
handleAddPlayer = () => {
// create a clone of your array of players; don't modify objects on the state directly
const players = this.state.players.slice(0);
players.push({
name: 'Maul',
id: 26
});
this.setState({
players: players,
});
};
这篇关于React使用.push通过onClick添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!