[英]Icon doesn't change on button toggle - React
FontAwesome 图标不会更新图标。 切换必须发生 onClick 的“就绪”按钮。 操作发生得很好,object 的 isReady 属性的 state 将值从 FALSE 更改为 TRUE 并反转。 任何想法为什么图标也不会更新?
let [gameData, setGameData] = useState(props[1]);
const toggleReady = (c) => {
const newGameData = gameData;
newGameData.clients[c].voteReady = !newGameData.clients[c].voteReady;
setGameData(newGameData);
console.log(gameData.clients[c].voteReady);
};
return (
<div>
<Header name="Waiting Room" />
<div className="centered">
<div className="players">
<h1>Lobby players:</h1>
{gameData.clients.map((c, index) => (
<div>
<div>
<h2 key={c.id}>
Player {index + 1}: {c.username}
</h2>
{c.voteReady === true ? (
<BsFillCheckCircleFill className="mark" />
) : (
<BsXCircleFill className="cross" />
)}
{c.id === clientId ? (
<button
className="btn btn-info btn-sm button-ready"
onClick={() => toggleReady(index)}
>
Ready?
</button>
) : null}
</div>
</div>
))}
</div>
</div>
</div>
);
};
这里发生的两件事是你正在改变 state,
对 useState 使用 const,因为它不应被视为可变值。
const [gameData, setGameData] = useState(props[1]);
您的 function 应该创建 gameData 的克隆,而不仅仅是将 gameData 分配给新变量,您可以使用扩展运算符来实现这一点。
const toggleReady = (c) => {
// Here you will create a copy of gameData and you'll not mutate the original.
const newGameData = { ...gameData };
newGameData.clients[c].voteReady = !newGameData.clients[c].voteReady;
setGameData(newGameData);
console.log(gameData.clients[c].voteReady);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.