繁体   English   中英

如何在我的反应应用程序中使用 useState 钩子给出的 setState 方法增加 state object 的选定索引的计数

[英]How do I increment the count of a selected index of state object using setState method given by useState hook in my react application

目的:当投票按钮发生点击事件时,将给定数组的索引更新 1

我的代码:我有一个应用程序组件,其中有 2 个 state 对象和 1 个数组

const App = () => {
    const anecdotes = [
        'If it hurts, do it more often',
        'Adding manpower to a late software project makes it later!',
        'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
        'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
        'Premature optimization is the root of all evil.',
        'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
    ]

    // to select anecdotes at random
    const [selected, setSelected] = useState(0);

    // elements in anecdotes
    let n = anecdotes.length;
    const [points, setPoints] = useState(() => Array(n).fill(0));

    // to use with setSelected 
    const generateRandomNumber = (min, max) => {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min) + min); 
    }

    // eventHandler
    const handleClickNext = () => {
        return setSelected(generateRandomNumber(0, n))
    }

    const handleClickVote = () => {
        const copy = [...points]
        console.log(copy);
        console.log(selected);
        console.log(copy[selected]);
        console.log(points);
        return setPoints([
            copy[selected] += 1
        ])
    }

    return (
        <>
            <h1>anecdoteZ</h1>
           // code...
        </>
    )
}

export default App;

目标:该应用程序显示来自轶事数组的随机引用以及轶事投票计数和为轶事投票的能力。

问题:我认为问题是我的handleClickVote function

 const handleClickVote = () => {
        const copy = [...points]
        console.log(copy);
        console.log(selected);
        console.log(copy[selected]);
        console.log(points);
        return setPoints([
            copy[selected] += 1
        ])
    }

该代码适用于显示的第一个轶事,但是当我单击next quote按钮并对其他引号进行投票时,它会在控制台中返回NaN ,因为我正在记录结果。 另外我认为我正在使用setPoints地设置数组的 state。 我不想直接改变 state,我想创建一个副本并改变它,而不是更新我的points数组的 state。

注意这是我的应用程序组件返回的

<>
            <h1>anecdoteZ</h1>
            <span anecdotes={anecdotes} selected={selected}>
                {anecdotes[selected]}
            </span>
            <br />
            <br />
            <span points={points} selected={selected}>has {points[selected]} votes</span>
            <br />
            <button onClick={handleClickVote}>vote</button>
            <button onClick={handleClickNext}>
                next anecdote
            </button>
            <br />
            <br />
            <span>Top voted anecdote</span>
        </>

方法handleClickVote将值设置为长度为1的数组。 我无法对其进行测试,但我建议将其更改为:

copy[selected] += 1;
return setPoints(copy);

你假设正确,问题是handleClickVote function。 就目前而言,在第一次投票中,您将 state 设置为一个只有一个元素的数组。

return setPoints([       // <<-- new array starts here
    copy[selected] += 1  // <<-- it's only element, will be the the result of
                         //      the increment of whatever is in copy[selected] plus 1
]);

您想要更新copy中的任何内容, copy分配为新的 state。 例如:

copy[selected]++;
return setPoints(copy);

或者(从https://stackoverflow.com/a/45673826借用),简单地说:

const handleClickVote = () => {
    return setPoints(current => Object.assign([], current, {
      [selected]: current[selected] + 1
    }));
}

首先,当您将轶事的长度传递给生成随机数时,它应该是anecdotes.length - 1

也无需返回setPoints - 这可能是您的问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM