gpt4 book ai didi

javascript - 从动态创建的子组件更改状态 - React

转载 作者:行者123 更新时间:2023-11-30 19:02:50 25 4
gpt4 key购买 nike

在此应用程序中,您可以通过单击特定游戏的 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>
);
}

}

匹配.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;

CodeSandBox

我认为我的问题出在 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 });
}

这是一个工作演示 https://codesandbox.io/s/practical-margulis-n0ch1

关于javascript - 从动态创建的子组件更改状态 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59326662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com