【发布时间】:2020-06-24 17:24:18
【问题描述】:
我正在使用 React 16.13。如何找到列表中的第一项?听起来很简单,但我试过了
let value = next(country.id for country in countries if country.code == this.props.countryCode)
这会导致错误
./src/components/Country.jsx
Line 9:37: Parsing error: Unexpected token, expected ","
7 | <option key={country.id} value={country.id}>{country.name}</option>
8 | );
> 9 | let value = next(country.id for country in countries if country.code == this.props.countryCode)
| ^
10 |
这是我的全部组件。 “countries”是一个对象列表,每个对象都有一个“code”和“id”属性。
class Country extends React.Component {
render () {
let countries = this.props.options;
let optionItems = countries.map((country) =>
<option key={country.id} value={country.id}>{country.name}</option>
);
let value = next(country.id for country in countries if country.code == this.props.countryCode)
return (
<div className="form-group">
<label htmlFor={this.props.name}> {this.props.title} </label>
<select
id = {this.props.name}
name={this.props.name}
value={value}
onChange={this.props.handleChange}
className="form-control">
<option value="" disabled>{this.props.placeholder}</option>
{optionItems}
</select>
</div>
)
}
}
【问题讨论】:
-
我不知道
next函数是什么,但array::find 通常用于查找符合条件的数组的第一个元素。该错误是因为它需要一个逗号分隔的函数参数列表,而不是几个表达式。整个表达式let value = next(country.id for country in countries if country.code == this.props.countryCode)是无稽之谈。你想做什么? -
我想找到列表中第一个“code”属性与传入组件的属性相匹配的国家/地区的ID。