【问题标题】:trouble setting state in reactjs在 reactjs 中设置状态时遇到问题
【发布时间】:2020-05-11 19:01:57
【问题描述】:

我有一个非常简单的代码来设置状态变量,但是遇到了麻烦。

https://codesandbox.io/s/highcharts-react-demo-rtlie

我看到 this.state.chart_options 显示在控制台上,但它为空。

代码:_

import React from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
import drilldow from "highcharts/modules/drilldown";
//import HighchartsReact from "./HighchartsReact.js";
import PieChart from "highcharts-react-official";
drilldow(Highcharts);
const options = {
  chart: {
    type: "pie"
  },
  series: [
    {
      data: [{ y: 100, name: "Female" }, { y: 50, name: "Male" }]
    }
  ]
};
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      chart_options: null
    };
    this.setState({ chart_options: options }, () => {
      console.log("this.state - ", this.state);
      console.log("options - ", options);
    });
  }
  onFilterClickHandler = () => {
    console.log("hi", this.state.chart_options);
  };
  render() {
    const key = 1;
    return (
      <div>
        <div>
          <label>
            <input
              type="checkbox"
              value={key}
              onClick={this.onFilterClickHandler}
            />
          </label>
        </div>
        <h2>Highcharts</h2>
        <PieChart highcharts={Highcharts} options={options} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

【问题讨论】:

  • stackoverflow.com/q/34961853/5108962 检查答案,你就会知道哪里出了问题。
  • 为什么在 constructor() 中使用 setState ?这是不好的做法!如果要为初始 this.state.chart_option 设置值“options”,则应在声明 this.state.chart_options = options 时设置它的方向。

标签: reactjs


【解决方案1】:

您在构造函数内部调用setState(当组件尚未安装时)。

要获得预期的console.log 输出,请从生命周期方法componentDidMount 中调用setState

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      chart_options: null
    };
  }

  componentDidMount() {
    this.setState({ chart_options: options }, () => {
      console.log("this.state - ", this.state);
      console.log("options - ", options);
    });
    console.log(this.state);
  }

  onFilterClickHandler = () => {
    console.log("hi", this.state.chart_options);
  };
  render() {
    const key = 1;
    return (
      <div>
        <div>
          <label>
            <input
              type="checkbox"
              value={key}
              onClick={this.onFilterClickHandler}
            />
          </label>
        </div>
        <h2>Highcharts</h2>
        <PieChart highcharts={Highcharts} options={options} />
      </div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多