reactjs - 如何使用 useState 钩子计算数组中项目的频率(React useState 钩子)?
问题描述
我正在尝试解决这个数组包含 10 个对象的练习,例如
arr = [{txt: "txt1", color: "red"},
{txt:“txt2”,颜色:“绿色”},{txt:“txt3”,颜色:“蓝色”},...]
当我单击一个按钮时,它应该显示一种我知道该怎么做的随机颜色,但我不确定如何也显示每种颜色出现的次数。
我将我的功能设置如下:
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>
)
};
当我使用反应开发工具检查状态时,我不断收到“NaN”或“未定义”。
我想知道是否需要设置 3 个状态来计算每种颜色。
解决方案
这是你需要做的:
const[redCount,setRedCount]=useState(0);
//similarily for other colors
const clickHandler = () => {
let randColor = choice(props.arr).color;
if (randColor === 'red') {
setRedCount(redCount+1);
//similairly do it for other colors
}
return (
<ul>
<li>Red Counts: {redCount}</li>
//similarily for other colors
</ul>
<button onClick={clickHandler}>Click</button>
)
推荐阅读
- laravel - 删除望远镜条目 Laravel 8
- python - 将变量从 html 5 表单传递到 python 代码
- webix - webix 上传器:捕获错误并再次上传文件
- elasticsearch - 升级到 7.9.0 时无法在 elasticsearch.xpack.security 中加载插件类
- php - PHP - 带有单引号或双引号的错误 base64 hmac sha256 编码
- django - ValueError at /like/ Field 'id' expected a number but got ''
- swift - 使用 ParseSwift 在 mongo DB 上进行查询
- nestjs - 为什么nestjs服务没有注入护照策略?
- flutter - 如何在飞镖图中添加重复键?
- c# - 使用代码在不同模式中的两个表之间进行实时映射