简体   繁体   English

如何在 ArrayObject React native 中设置状态数组

[英]How to setState Array in ArrayObject React native

I've been sitting around for a while trying to figure out how to do this I've scoured a lot of documentation on StackOverFlow (maybe I missed it)我已经坐了一段时间试图弄清楚如何做到这一点我已经搜索了很多关于 StackOverFlow 的文档(也许我错过了)

this.state = {
        data: {
                labels: [],
                datasets: [
                    {
                        data: []
                    }
                ]
            }
        };

i tried with below code how can i setState CONCAT for 2 arrays Labels:[] and data:[]我尝试使用以下代码如何为 2 个 arrays 标签:[] 和数据:[] setState CONCAT

my code:我的代码:

  this.setState(a => ({
       data: {
          labels: this.state.data.labels.concat(x.month), <- is this correct?
          datasets: [
                      {
                        data: this.state.data.datasets.map(x=> x.data.concat(x.money/1000))
                     or //data: this.state.data.datasets[0].data.concat(x.money/1000))
                       }
                    ]
              }
           }
        )
     )

JS JS

data: {

                labels: [],
                datasets: [
                    {
                        data: []
                    }
                ]
       }

how to point to data array?如何指向数据数组?

As you might be aware, the state update in react/react-native are asynchronous.您可能知道,react/react-native 中的 state 更新是异步的。 Therefore the code you have written might cause some weird behavior sometimes.因此,您编写的代码有时可能会导致一些奇怪的行为。 For example, simultaneously multiple function call for that state update might lead to the unexpected end state.例如,同时多个 function 调用 state 更新可能会导致意外结束 state。

Instead, you can update your state as following相反,您可以更新您的 state 如下


this.setState((state, props) => ({
   data: {
      labels: state.data.labels.concat(x.month),
      datasets: state.data.datasets.map(({data}) => ({data: data.concat(x.money/1000)}))
    }
  })
)

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

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