Using react-select I've got next issue: Cannot read property 'value' of undefined

那年仲夏 提交于 2021-01-19 10:11:48

问题


I'm using react-select. When I'm selecting a determinate value from select I've got the next issue

TypeError: Cannot read property 'value' of undefined

Also, values fetched from reducer todoList are not showed, I can't see them.

This is my code:

import Select from "react-select";
import "./styles.css";
import { searchTodos } from "../../actions/ServiceActions";

class SelectedTodo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedTodo: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }
  bringTodos = () => {
    //WHEN I'M EXECUTING THESE CODE LINES I CAN'T SEE TODOS VALUES
    return this.props.todoList.map(todo => {
      return (
        <option key={todo._id} value={todo._id}>
          {todo.name}
        </option>
      );
    });
  };

  handleChange = e => {
    this.setState({ selectedTodo: e.target.value });
  };

  componentDidMount() {
    this.props.searchTodos();
  }

  render() {
    const { loading } = this.props;

    if (loading) {
      return <span>...Loading</span>;
    }
    return (
      <Select
        className="form-container"
        classNamePrefix="react-select"
        placeholder="Please, insert a todo"
        value={this.state.selectedTodo}
        onChange={this.handleChange}
        options={this.bringTodos()}
      />
    );
  }
}

function mapState(state) {
  return {
    todoList: state.todosDs.todoList
  };
}
const actions = {
  searchTodos
};
SelectedTodo = connect(
  mapState,
  actions
)(SelectedTodo);

export default SelectedTodo;

The expected behavior is dropdown shows todos and when I'm selecting a todo value I'm not getting error

TypeError: Cannot read property 'value' of undefined


回答1:


The package react-select directly returns the json that has the value like

{label:"ABC", value:"abc"}

Change this

  handleChange = (e) =>{
  this.setState({selectedTodo: e.target.value});
  }

To this

handleChange = (e) =>{
  this.setState({selectedTodo: e});
  }



回答2:


I think as the documentation of react-select says

 <Select
    value={selectedOption}
    onChange={this.handleChange}
    options={options}
  />

this.handleChange will directly return the selected option rather then event object.

    handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

and I think you don't need to bind the handleChange method as well.



来源:https://stackoverflow.com/questions/60488902/using-react-select-ive-got-next-issue-cannot-read-property-value-of-undefine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!