简体   繁体   English

如何更新嵌套的useState?

[英]how to update nested useState?

Hey there im having an issue on updating the useState.嘿,我在更新 useState 时遇到问题。 I saw some example but when trying to implement it it does not work.. Anyone can give me a hand on sorting this little issue?我看到了一些例子,但是在尝试实现它时它不起作用。任何人都可以帮我解决这个小问题吗?

this is the original state and i need to update labels这是原始 state,我需要更新标签

        setChartData({
            labels: [ ],
            datasets:[
            {
                label:'Sales',
                data:[ //values for population num
                    
                ],
                backgroundColor:[
                    'rgba(255, 99, 132, 0.6)',
                    'rgba(54, 162, 235, 0.6)',
                    'rgba(255, 206, 86, 0.6)',
                    'rgba(75, 192, 192, 0.6)',
                    'rgba(153, 102, 255, 0.6)',
                    'rgba(255, 159, 64, 0.6)',
                    'rgba(255, 99, 132, 0.6)'
                ]
            }
            ]
        })

this is the array im trying to assign to labels array这是我试图分配给标签数组的数组

        for (let y = 0; y < weeks.length; y++) {
            setChartData(prevState => ({
                ...prevState,
                labels: {
                    ...prevState.labels,
                    weeks[y]
                }
            }))
        }

Oops: You've used the wrong braces in your loop!糟糕:您在循环中使用了错误的大括号! Try this:尝试这个:

for (let y = 0; y < weeks.length; y++) {
  setChartData((prevState) => ({
    ...prevState,
    labels: /* { */ [
      ...prevState.labels,
      weeks[y]
    ] /* } */
  }));
}

You were replacing your labels array with an object using an invalid syntax, this is probably what you meant to do.您正在使用无效语法将您的labels数组替换为 object,这可能是您的本意。

Try without taking the prevState as an argument in the callback, like this:尝试不将prevState作为回调中的参数,如下所示:

for (let y = 0; y < weeks.length; y++) {
            setChartData(() => ({
                ...chartData //or whatever you called your state variable.
                labels: {
                    ...chartData.labels,
                    weeks[y]
                }
            }))
        }

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

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