this.setState不更改状态值

时间:2019-12-09 19:45:17

标签: javascript reactjs

ageVSpqiYearPick是一个变量,它决定选择哪个背景层(功能selectBackgroundLayer())。选择菜单项后,ageVSpqiYearPick被设置。使用当前代码,setState不会更改变量。 console.log是:

  

'selectBackgroundLayer:,2021'

this.state = {   //in constructor
  ageVSpqiYearPick: ''  
};

<MenuItem  //these menu items are located in render method
  key="Age"
  text="Age"
  onClick={() => {
    this.props.selectBackgroundLayer('Age');
    this.setState({ ageVSpqiYearPick: "Age" });
    console.log("Setting AGE"); 
  }}
/>

<MenuItem
  key="PSR"
  text="PQI - Pavement Quality Index"
  onClick={() => {
    this.setState({ ageVSpqiYearPick: 'getPQI' }, () => { this.props.selectBackgroundLayer('getPQI'); });
    console.log("Setting PQI");
  }}
/>
//this is a handling function for a dropdown selector for changing the year
onChangeDropdownPQI = (e) => {  
  const { target } = e;  
  const { name, value } = target;

  console.log("selectBackgroundLayer: " + this.state.ageVSpqiYearPick + " ," + value);
  this.selectBackgroundLayer(this.state.ageVSpqiYearPick,value); 
}

2 个答案:

答案 0 :(得分:0)

onClick更改为onSelect

<MenuItem key="Age" text="Age"
                    onSelect={() => { this.props.selectBackgroundLayer('Age');  this.setState({ ageVSpqiYearPick: "Age" }); console.log("Setting AGE"); }} />

<MenuItem key="PSR" text="PQI - Pavement Quality Index"
                    onSelect={() => { this.setState({ ageVSpqiYearPick: 'getPQI' }, () => { this.props.selectBackgroundLayer('getPQI'); }); console.log("Setting PQI");} } />

答案 1 :(得分:0)

this.state = ...放置在构造函数中,如下所示:

import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {ageVSpqiYearPick: ''}
  }

  render() {
    return (
      <div className="App">
        <a href="facebook.com" onClick={
          () => this.setState(
              {ageVSpqiYearPick: 'getPQI'},
              function () {
                console.log(this.state);
              })
          }>Visit facebook.com!</a>

      </div>
    );
  }

}

export default App;