我有数组cities与这样的对象:
[{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>
);
}
}
我有一个错误:
未捕获的类型错误:无法读取未定义的属性“名称”
我该如何修复它?
看来你需要filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)