简体   繁体   中英

Why react-select doesn't work with options from state?

This code works ok, because options are outside:

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState(
      { selectedOption },
      () => console.log(`Option selected:`, this.state.selectedOption)
    );
  };
  render() {
    return (
      <Select
        value={this.state.selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

but this code, doesn't work, because options are inside the state

import React from 'react';
import Select from 'react-select';

class App extends React.Component {
  state = {
     options: [
       { value: 'chocolate', label: 'Chocolate' },
       { value: 'strawberry', label: 'Strawberry' },
       { value: 'vanilla', label: 'Vanilla' },
    ],
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState(
      { selectedOption },
      () => console.log(`Option selected:`, this.state.selectedOption)
    );
  };
  render() {    
    return (
      <Select
        value={this.state.selectedOption}
        onChange={this.handleChange}
        options={this.state.options}
      />
    );
  }
}

If i use options from state, console log inside handleChange not return selectedOption. Tell me please, why? I want to use this plugin with options from state...

Replace options = [ with options: [ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM