首页 > 解决方案 > 如何使用 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 个状态来计算每种颜色。

标签: reactjsreact-hooksuse-state

解决方案


这是你需要做的:

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>

 )

推荐阅读