setState到对象内部的Array

时间:2019-02-19 14:34:45

标签: reactjs react-native

这是我在Chart组件中的状态。我从我的数据库(带有componentDidMount)中获取城市数据和关注者数据,我想将城市设置为chartData内部的lables数组,并将关注者(具有数字的数组)设置为数据数组,但是我无法获取它完成。最好的方法是什么?

state = {
  chartData: {
    labels: [here],
    datasets: [
      {
        label: 'Population',
        data: [here],
        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)'
        ]
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:3)

确保在datasets数组中只有一个对象要添加关注者,您可以像这样更新状态:

class App extends React.Component {
  state = {
    chartData: {
      labels: [],
      datasets: [
        {
          label: "Population",
          data: [],
          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)"
          ]
        }
      ]
    }
  };

  componentDidMount() {
    setTimeout(() => {
      this.setState(prevState => {
        const cities = ["foo", "bar", "baz"];
        const followers = [1, 2, 3];

        return {
          chartData: {
            ...prevState.chartData,
            labels: cities,
            datasets: [
              {
                ...prevState.chartData.datasets[0],
                data: followers
              }
            ]
          }
        };
      });
    }, 2000);
  }
  
  render() {
    return <div>{JSON.stringify(this.state)}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>