1

我正在使用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;

When one of the options is selected it won't console.logthe new state however if I select the option again it will. 知道我哪里出错了,我猜是因为状态没有显示在 console.log 中,它没有更新?

谢谢

4

1 回答 1

6

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

_onChange(value) {
    //console.log(value) - just to see what we recive from <Select />
    this.setState({brandSelect: value}, () => {
        console.log(this.state.brandSelect);
    });
  }
于 2016-07-26T08:07:14.640 回答