在此应用中,您可以通过单击GOAL
特定游戏的按钮来更改足球比赛得分。问题是我的匹配项保存在状态中,并且使用map
方法渲染它们,而我不能为每个匹配项动态使用setState。
App.js
import React from 'react';
import Match from './components/Match';
import './App.css';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
games: [
{
home: {
team: "Bruges",
score: 0
},
guests: {
team: "Real Madrid",
score: 0
}
},
{
home: {
team: "Atletico Madrid",
score: 0
},
guests: {
team: "Lokomotiv",
score: 0
}
}
]
};
this.goal = this.goal.bind(this);
};
goal(parent) {
let rand = Math.round(Math.random());
if(rand) {
this.setState((prevstate) => ({parent: prevstate.parent.home.score + 1}))
} else {
this.setState((prevstate) => ({parent: prevstate.parent.guests.score + 1}))
}
}
render() {
return (
<div className="App">
{this.state.games.map((item, index) => {
return (<Match
key={index}
home={item.home.team}
homeScore={item.home.score}
guests={item.guests.team}
guestsScore={item.guests.score}
goal={() => this.goal(item)}
/>);
})}
</div>
);
}
}
Match.js
import React from 'react';
import '../App.css'
const Match = props => {
return(
<div className="match-container">
<span className="name-container">{props.home} </span>
<span className="score-container">{props.homeScore}</span>
<button onClick={props.goal}>GOAL</button>
<span className="score-container">{props.guestsScore} </span>
<span className="name-container">{props.guests} </span>
</div>
);
}
export default Match;
我认为我的问题出在goal
方法上,因为我认为我不能传递参数并将其用于setState
。
我没有找到与此特定问题相关的答案。
问题是您试图像将其作为对象一样更新数组。事实是您已将游戏设置为状态数组。这是您如何更新它:
goal(parent) {
let rand = Math.round(Math.random());
const { games } = this.state;
const index = games.findIndex(element => element === parent);
const newGames = [...games];
if (rand) {
newGames[index].home.score = newGames[index].home.score + 1;
} else {
newGames[index].guests.score = newGames[index].guests.score + 1;
}
this.setState({ games: newGames });
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句