React prop仅在选择两次后改变状态

时间:2016-07-26 08:04:56

标签: reactjs react-select

我正在使用React Select,由于某种原因,我的状态仅在选择了两次选项后才会更改。

我有以下代码:

var React = require('react');
import Select from 'react-select';

class VehicleSelect extends React.Component {

  constructor(props) {
    super(props);

    this.state = { brandSelect: ""};

  }

  _onChange(value) {
    //console.log(value) - just to see what we recive from <Select />
    this.setState({brandSelect: value});
    console.log(this.state.brandSelect);
  }

  render() {
    var options = [
    { value: 'Volkswagen', label: 'Volkswagen' },
    { value: 'SEAT', label: 'SEAT' },
    { value: 'SKODA', label: 'SKODA' }
    ];


    return (
      <Select
          name="form-field-name"
          value={this.state.brandSelect}
          options={options}
          placeholder="Select a brand"
          searchable={false}
          onChange={this._onChange.bind(this)}
      />
    )
  }
};

// Export our component
export default VehicleSelect;

当选择其中一个选项时,它不会console.log新状态,但是如果我再次选择该选项,它将会。我知道我哪里出错了,我猜测因为状态没有显示在console.log中它是不是在更新?

由于

1 个答案:

答案 0 :(得分:5)

setState不会立即改变状态。你需要使用回调。 Docs

_onChange(value) {
    //console.log(value) - just to see what we recive from <Select />
    this.setState({brandSelect: value}, () => {
        console.log(this.state.brandSelect);
    });
  }