在 useEffect 中从数组中添加数字

我正在尝试使用钩子将数组中的数字相加。目前它是一个投票系统。使用 map 语句添加所有数字的结果给我 0。我很确定这与 useState 没有及时更新以添加数字有关,因此它总是给我零。我知道我可以将它们放在一个单独的数组中,然后添加它,但是对于看起来如此简单的东西来说,这似乎有点冗长。


这是我拥有的产生 0 的代码


const PollResultsContainer = (props) => {

    const option = props.option

    const [totalVotes, setTotalVotes] = useState(0)


    useEffect(() => {

        let newVote

        if (option.length > 0) {

            option.map(opt => {

                newVote = opt.optionVotes + totalVotes

            })

        }

        setTotalVotes(newVote)

    }, [totalVotes])

    console.log(totalVotes)

    return (

        <>

            <div className='poll-results-div'>

                <TitleCardNS title={`${totalVotes}`} size='2.5rem' align='center' color='white' />

            </div>


吃鸡游戏
浏览 192回答 3
3回答

慕慕森

不需要用状态收藏。const PollResultsContainer = ({option}) => {&nbsp; let totalVotes = option.reduce((acc, {optionVotes}) => acc + optionVotes, 0);&nbsp; console.log(totalVotes);};

FFIVE

我认为您在此组件中不需要任何状态或效果:const PollResultsContainer = (props) => {&nbsp; &nbsp; const option = props.option&nbsp; &nbsp; let totalVotes = 0;&nbsp; &nbsp; if (option.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; option.forEach(opt => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; totalVotes += opt.optionVotes&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; console.log(totalVotes)

幕布斯6054654

我在等式中添加了另一个变量。这大概解决了useState没有及时更新的问题。const PollResultsContainer = (props) => {&nbsp; &nbsp; const option = props.option&nbsp; &nbsp; const [totalVotes, setTotalVotes] = useState(0)&nbsp; &nbsp; let newVote = 0&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; if (option.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; option.map(opt => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newVote = opt.optionVotes + newVote&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(newVote)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; console.log(newVote)&nbsp; &nbsp; &nbsp; &nbsp; setTotalVotes(newVote)&nbsp; &nbsp; }, [totalVotes])&nbsp; &nbsp; console.log(totalVotes)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript