[英]How to find object in array and show it in React component?
我有很多城市有這樣的對象:
[{id: 1, name: 'New York'}, {id: 2, name: 'London'} ...]
我有一個id值。
我將數組中的元素(名稱)放入選擇列表。 但是我需要添加第一個選項,其中包含數組(名稱)中的值,該值具有相應的 id,但我無法使其工作。
我的組件:
const propTypes = {
cities: PropTypes.array,
enteredEvent: PropTypes.array
};
class newEvent extends Component {
constructor(props) {
super(props);
this.state = {
showInOption: ''
};
this.handleDictionary = this.handleDictionary.bind(this);
this.searchTypeEvent = this.searchTypeEvent.bind(this);
}
componentDidMount() {
this.searchTypeEvent();
}
handleDictionary(e) {
...
}
searchTypeEvent() {
if (this.props.enteredEvent.cityid !== null && this.props.enteredEvent.cityid !== undefined) { // if I have id value
const type = this.props.cities.find(el => el.id === this.props.enteredEvent.cityid); // find an object with id
this.setState({ showInOption: type.name });
}
this.setState({ showInOption: 'Select something' });
}
render() {
return (
<div>
<select onChange={this.handleDictionary}>
<option>{this.state.showInOption}</option> // here I need to add a value
{this.props.cities.map(item => { // here I call other options
return (<InputSelect key={item.id} directory={item}/>);
})}
</select>
</div>
);
}
}
我有一個錯誤:
未捕獲的類型錯誤:無法讀取未定義的屬性“名稱”
我該如何解決?
嘗試這個
const type = Array.isArray(this.props.cities) && this.props.cities.find(el => el.id ==this.props.enteredEvent.cityid);
this.setState({ showInOption: type ? type.name : null });
確保您輸入的名稱與數組中的任何一個對象匹配
看來你需要filter 。它會返回一個對象數組
let a = [{ id: 1, name: 'New York' }, { id: 2, name: 'London' }] function b(idToSearch) { return a.filter(item => { return item.id === idToSearch }) }; console.log(b(1))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.