【问题标题】:Cannot read property 'paginationOption' of undefined in React Bootstrap Typeahead无法读取 React Bootstrap Typeahead 中未定义的属性“paginationOption”
【发布时间】:2019-09-11 18:53:19
【问题描述】:

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>
    );
  }
}

【问题讨论】:

  • @barbsan 错误已消失,但输入默认为空

标签: javascript reactjs typeahead react-bootstrap-typeahead


【解决方案1】:

您的所有者在初始渲染时是 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>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 1970-01-01
    • 2023-04-08
    • 2013-12-08
    • 2017-12-02
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    相关资源
    最近更新 更多