So this is my state in my Chart component. i'm getting citys data and followers data from my database (with componentDidMount)and i want to set the citys to the the lables array inside the chartData and the followers (array with numbers) to the data array, but i just cant get it done. what is the best way to do it?
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)'
]
}
]
}
}
Granted that you only have one object in the datasets
array that you want to add the followers to, you could update your state like this:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.