我使用React bootstrap Typeahead库(https://github.com/ericgio/react-bootstrap-typeahead)。我的问题是,基于索引this.state.todo
,我需要在this.state.todos
内部查找具有给定索引的对象。在多选中将找到的对象的名称显示为默认值。
此处演示:https://stackblitz.com/edit/react-rsfpup
class App extends Component {
constructor() {
super();
this.state = {
todos: [{id:1, name: 'Paul'}, {id:2, name: 'Martin'}, {id:3, name: 'Jacob'}],
todo:[1, 3],
selectedItems: []
};
}
handleSelect = items => {
this.setState({ selectedItems: items });
};
render() {
return (
<div>
<Todos
todos={this.state.todos}
todo={this.state.todo}
handleSelect = {this.handleSelect}
/>
</div>
);
}
}
class Todos extends Component {
constructor(props) {
super(props);
}
render() {
var tempArr = this.props.todos.filter(item => !this.props.todo.includes(item));
return (
<div>
<Typeahead
id={'example4'}
labelKey="name"
multiple
selected={tempArr}
options={this.props.todos}
onChange={this.props.handleSelect}
/>
</div>
);
}
}
答案 0 :(得分:2)
我认为您正在寻找这个
let selected = this.state.todos.map( (todo, index) => {
if(this.state.todo.includes(index)){ //compare based on index
return todo
}
})
如果要基于id
中的this.state.todos
进行比较,
let selected = this.state.todos.map( (todo, index) => {
if(this.state.todo.includes(todo.id)){ //compare based on id in this.state.todos
return todo
}
})
更新
根据您的演示示例,您只需要在selectedItems
组件中设置App
,并将其传递给Todos
组件。
componentDidMount(){
//Based on index
this.setState({
selectedItems: this.state.todos.filter( (todo, index) => this.state.todo.includes(index))
})
//Based on id in this.state.todos
// this.setState({
// selectedItems: this.state.todos.filter( (todo, index) => this.state.todo.includes(todo.id))
// })
}
注意:,您需要在此处使用map
,而不是filter
。
将selectedItems
传递到Todos
组件,
<Todos
todos={this.state.todos}
todo={this.state.todo}
handleSelect = {this.handleSelect}
selectedItems = {this.state.selectedItems} //Pass selectedItems here
/>
在Todos
组件中,您需要使用selectedItems
<Typeahead
id={'example4'}
labelKey="name"
multiple
selected= {this.props.selectedItems} //Use selectedItems here
options={this.props.todos}
onChange={this.props.handleSelect}
/>
答案 1 :(得分:0)
我认为问题是因为todos是一个对象数组,而todo是一个整数数组,因此,当您执行过滤器时,它将不起作用,您将不得不使用todos.id。例如:
var tempArr = this.props.todos.filter(item => !this.props.todo.includes(item.id));