在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>
);
}
}
答案 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>
);
}
}