React 道具仅在选择两次后更改状态

React prop only changes state after selecting twice

我正在使用 React Select,出于某种原因,我的状态仅在某个选项被 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;

当其中一个选项被 select 编辑时,它不会 console.log 新的状态,但是如果我再次 select 选项它会。知道我哪里出错了,我猜是因为 console.log 中没有显示状态,它没有更新吗?

谢谢

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

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