【发布时间】:2018-11-13 14:35:28
【问题描述】:
我有一系列 城市 对象如下:
[{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>
);
}
}
我有一个错误:
未捕获的类型错误:无法读取未定义的属性“名称”
我该如何解决?
【问题讨论】:
-
您试图通过查看 id 来通过搜索词查找项目,这是故意的吗?
el.id === this.props.enteredEvent.cityname。您还必须确保在尝试访问name之前确实找到了type。 -
不知道
cityname是什么。如果它来自输入,那么它不太可能是一个可以通过===检查的数字。 -
@Tholle this.props.enteredEvent.cityid 是正确的。我在帖子中的错误。我得到了我需要的对象(在找到之后),但我无法获得名称值
-
@estus this.props.enteredEvent.cityid 是正确的。我在帖子中的错误
-
在
find之后写console.log(type);,您将得到undefined,如错误所示。我认为防止cityid与cities对象ID 不匹配的情况是个好主意。
标签: javascript reactjs