小编典典

反应:setState无法获得预期的结果(不起作用?)

reactjs

我的项目是Cordova + React(es6)。我在使用setState()时遇到一些问题。

传递给状态的数据不为空。但是,将数据传递给状态时,我收到的结果状态为空。

我项目的env(package.json):

{
  "name": "MYAPP",
  "version": "1.0.0",
  "description": "this is front of simula's app",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "browserify ./www/jsx/app.jsx -t babelify -o ./www/js/app.js"
  },
  "author": "maki",
  "license": "ISC",
  "dependencies": {
    "babel-preset-es2015": "^6.13.2",
    "browserify": "^13.1.0",
    "gulp": "^3.9.1",
    "history": "^4.2.0",
    "material-design-icons": "^2.2.3",
    "material-ui": "^0.15.4",
    "rd3": "^0.7.2",
    "react": "^15.3.0",
    "react-d3": "^0.4.0",
    "react-dom": "^15.3.1",
    "react-motion": "^0.4.4",
    "react-router": "^2.7.0",
    "react-swipeable-views": "^0.7.0",
    "react-tap-event-plugin": "^1.0.0",
    "vinyl-source-stream": "^1.1.0"
  },
  "devDependencies": {
    "babel-cli": "^6.11.4",
    "babel-plugin-transform-class-properties": "^6.11.5",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-1": "^6.13.0",
    "babelify": "^7.3.0",
    "gulp-sass": "^2.3.2",
    "jquery": "^3.1.0"
  }
}

而我的代码:

export default class SomeCard extends React.Component {
  constructor(){
    super();

    this.state = {
      data_source: []
    }
  }

  componentDidMount(){
    const {name, data} = this.props.data;
    if(name == 'AAA'){
      let values_a = data.map((tmp_data) =>{
        let date = new Date(tmp_data.date);
        return {
          x: date,
          open: tmp_data.open,
          high: tmp_data.high,
          low: tmp_data.low,
          close: tmp_data.close
        };
      });
      let final_tmp_data = [
        {
          name: name,
          values: values_a
        }
      ];
      console.log(final_tmp_data);  //NOT EMPTY
      this.setState({data_source: final_tmp_data});
      console.log(data_source);     //NOT EMPTY
    }else if(name == 'BBB'){
      let values_b = data.map((tmp_data) => {
        let date = new Date(tmp_data.date);
        let tmp_date = date.getFullYear();
        return {
          "x": String(tmp_date),
          "y": tmp_data.value
        };
      });
      let final_cash_data = [
        {
          "name": name,
          "values": values_b
        }
      ];
      console.log(final_cash_data);          //NOT EMPTY
      this.setState({data_source: final_cash_data});
      console.log(this.state.data_source);   //EMPTY!!!!!!!!
    }
  .....
}

我该怎么办???


阅读 373

收藏
2020-07-22

共1个答案

小编典典

React setState()是一个异步操作,因此在您的代码中调用它后,它不会立即交付结果。如果 在render()*
方法中添加仅在完成时调用的 状态 ,则可以 访问更新后的状态console.log(this.state.data_source);
*this.setState()

看看React文档:https ://facebook.github.io/react/docs/component-
api.html#setstate

setState()不会立即更改this.state,但会创建一个挂起的状态转换。调用此方法后访问this.state可能会返回现有值。有
没有对setState调用同步运行的保障 ,呼叫可能会分批进行性能提升。

*除非在shouldComponentUpdate()中实现了条件渲染逻辑,否则 *setState()将始终触发重新渲染

2020-07-22