无法读取React Bootstrap Typeahead中未定义的属性'paginationOption'

时间:2019-09-11 10:33:02

标签: javascript reactjs typeahead react-bootstrap-typeahead

todos数组中,它查找带有id 4的元素。他将其写入owner变量。我将owner变量放入了newArray数组中。然后,我将newArray放在selected = {newArray.slice (0, 1)}中。我想在输入中将owner显示为默认值。我使用的是图书馆:React Bootstrap Typeahead

演示:https://stackblitz.com/edit/react-agfvwn?file=index.js

我有错误:

  

无法读取未定义的属性'paginationOption'

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: []
    };
  }

  componentDidMount() {
    this.getTodos();
  }

  getTodos = () => {
    axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: "GET"
    })
    .then(res => { 
      this.setState({
        todos: res.data
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  render() {
    console.log(this.state.todos)
    const owner = this.state.todos.find(todo => todo.id === 4)

    const newArray = [];
    newArray.push(owner)

    return (
      <div>
        <Typeahead
          id={'sasas'}
          selected={newArray.slice(0,1)}
          labelKey="title"
          options={this.state.todos}
          ref={(ref) => this._typeahead = ref}
        />
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您的所有者是undefined,因为getTodos尚未完成,并且this.state.todos是空数组。

获取数据后,应设置所选项目,例如:

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: [],
      selected: []
    };
  }

  componentDidMount() {
    this.getTodos().then(() => {
      const todo = this.state.todos.find(todo => todo.id === 4);
      this.setState({
        selected: todo ? [todo] : []
      })
    })

  }

  getTodos = () => {
    return axios({
      url: 'https://jsonplaceholder.typicode.com/todos',
      method: "GET"
    })
    .then(res => { 
      this.setState({
        todos: res.data
      });
    })
    .catch(error => {
      console.log(error);
    }) 
  }

  render() {
    return (
      <div>
        <Typeahead
          id={'sasas'}
          selected={this.state.selected}
          labelKey="title"
          options={this.state.todos}
          ref={(ref) => this._typeahead = ref}
        />
      </div>
    );
  }
}