我的状态没有从 call 变为 call1

My state is not changing to call1 from call

我想制作一个DynamicBarChart,但我无法更新状态。你能找出原因吗?

import React, { Component } from 'react';
import { DynamicBarChart } from 'react-dynamic-charts';
import 'react-dynamic-charts/dist/index.css';

class Dynamicchart extends Component {
  constructor(props) {
    super(props)

    this.state = {
      data: [{ "name": "Call", "values": [] }]
    }
  }

  componentDidMount = async () => {
    const mockData = [
      {
        id: 1,
        value: 10,
        label: "hey",
        color: "red"
      }
    ]
    const newwData = [{
      "name": "Call1",
      "values": mockData // Here i changed the values of the data
    }]

    this.setState({
      data: newwData // This method is unable to change the state.data component
    });

    // This still gives the value of data which is given in constructor 
    // Why has the value not changed?
    console.log(this.state.data) 
  }

  render() {
    return (
      <DynamicBarChart
        data={this.state.data}
      />
    );
  }
}

export default Dynamicchart

这段代码在前端显示"Call",我想要"Call1"的值。这意味着状态没有改变。你能解释一下为什么会这样吗?

setState 是一个 Async 操作,所以你必须使用 callbacksetState 之后做任何事情,在回调中以这种方式使用 console.log()或将 console.log 放入渲染函数中。

    const newwData = [{
      "name": "Call1",
      "values": mockData
    }]

    this.setState({
      data: newwData
    }, () => console.log(this.state.data));

将随机 key 添加到 DynamicBarChart 组件将解决问题:

    return <DynamicBarChart key={Math.random()} data={this.state.data} />;

我创建了一个沙箱来演示这个 Example with Simulated API Request 中的假延迟。


也就是说,@Waheed 的评论是有效的,关于在调用 this.setState({...}) 之后立即访问 this.state.data,因为后者是异步的。如果您想查看数据更新,请使用 render() 块中的 console.log 或作为 setState 的回调,就像@Waheed 在他的回复中提到的那样。

组件未重新呈现的原因是您正在使用新数据改变状态。通过设置随机密钥,您将强制 DynamicBarChart 组件重新渲染。