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);
}
答案 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;