【问题标题】:In React, how do I find the first item in a list that matches some criteria?在 React 中,如何在列表中找到符合某些条件的第一项?
【发布时间】: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。

标签: arrays reactjs filter


【解决方案1】:

问题

错误是因为它需要一个逗号分隔的函数参数列表,而不是几个表达式。

解决方案

使用array::find 搜索数组并返回匹配条件/谓词的第一个元素,如果未找到匹配项,则返回undefined。由于可以返回undefined,因此您需要在访问属性之前先检查结果,例如code

let countries = this.props.options;
let optionItems = countries.map((country) =>
  <option key={country.id} value={country.id}>{country.name}</option>
);

const country = countries.find(country => country.code === this.props.countryCode);
const countryCode = country ? country.code : null;

let value = next(country.id, countryCode);

【讨论】:

    【解决方案2】:
    const found = countries.find(country => country.code === this.props.countryCode)
    

    【讨论】:

      【解决方案3】:
      let value = country.filter(con=>(country.code === this.props.countryCode));
      

      您可以像这样访问所需结果国家/地区的值

      value[0].id;
      

      【讨论】:

        猜你喜欢
        • 2013-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多