【发布时间】:2019-01-23 09:47:59
【问题描述】:
我想切换数组中对象的属性。数组如下所示。这是在反应组件中使用的,当用户单击按钮时,我想切换获胜者。
const initialFixtures = [{
teams: {
home: 'Liverpool',
away: 'Manchester Utd'
},
winner: 'Liverpool'
},
{
teams: {
home: 'Chelsea',
away: 'Fulham'
},
winner: 'Fulham'
}, ,
{
teams: {
home: 'Arsenal',
away: 'Tottenham'
},
winner: 'Arsenal'
}
];
我的反应代码看起来像这样
function Parent = () => {
const [fixtures, setUpdateFixtures] = useState(initialFixtures)
const toggleWinner = (index) => {
const updatedFixtures = fixtures.map((fixture, i) => {
if (i === index) {
return {
...fixture,
winner: fixture.winner === home ? away : home,
};
} else {
return fixture;
}
})
setUpdateFixtures(updatedFixtures);
}
return <Fixtures fixtures={fixtures} toggleWinner={toggleWinner} />;
}
function Fixtures = ({ fixtures, toggleWinner }) => {
fixtures.map((fixture, index) => (
<div>
<p>{fixture.winner} </p>
<button onClick = {() => toggleWinner(index)}> Change Winner</button>
</div>
))
}
代码有效,但感觉有点太多了。我相信有更好更简洁的方法来做到这一点。任何人都可以建议吗?出于架构原因,我确实需要从 Fixture 组件的父级传递固定装置。
【问题讨论】:
-
changeWinner函数在哪里? -
在哪里声明了
home和away变量? -
代码有效,但感觉有点过头了。 代码审查请求在这里是题外话。看CR
-
快速提问。这是怎么回事:
function Parent = () => {工作?? -
它是一个在App中渲染的功能组件。如果这是您要的,它正在使用 Hooks?
标签: javascript arrays reactjs ecmascript-6