【发布时间】:2021-04-04 04:02:29
【问题描述】:
我正在尝试解决这个数组包含 10 个对象的练习,例如
arr = [{txt: "txt1", color: "red"},
{txt: "txt2", 颜色: "green"}, {txt: "txt3", 颜色: "blue"},...]
当我点击一个按钮时,它应该显示一种我知道该怎么做的随机颜色,但我不确定如何同时显示每种颜色出现的次数。
我的功能设置如下:
const countColors = (props) => {
const arr = [{txt: "txt1", color: "red"},
{txt: "txt2", color: "green"}, {txt: "txt3", color: "blue"},...]
const [count, setCount] = useState(0);
const choice = () => {
const randIdx = Math.floor(Math.random() * arr.length);
return arr[randIdx];
};
const updateScore = () => {
let randColor = choice(props.arr).color;
if (randColor === 'red') {
return setCount((count) => count + 1)
} else if (randColor === 'green') {
return setCount((count) => count + 1);
} else {
return setCount((count) => count + 1);
}
};
const clickHandler = () => {
setCount(updateScore);
}
return (
<ul>
<li>Red Counts: {updateScore}</li>
<li>Green Counts: {updateScore}.
</li>
<li>Blue Counts: {updateScore}</li>
</ul>
<button onClick={clickHandler}>Click</button>
)
};
当我使用 react 开发工具检查状态时,我不断收到“NaN”或“未定义”。
我想知道是否需要设置 3 个状态来计算每种颜色。
【问题讨论】:
标签: reactjs react-hooks use-state