【问题标题】:How to find object in array and show it in React component?如何在数组中查找对象并将其显示在 React 组件中?
【发布时间】: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,如错误所示。我认为防止cityidcities 对象ID 不匹配的情况是个好主意。

标签: javascript reactjs


【解决方案1】:

看来你需要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))

【讨论】:

  • 我需要打印名称值。我该怎么做?
【解决方案2】:

试试这个

  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 });

确保您输入的名称与数组中的任何一个对象匹配

【讨论】:

  • 当我从选项调用这个函数并在函数中返回值时,这个函数调用了 6 次,在最后一次调用中我得到了对象值(我使用 console.log 捕获它)。也许 React 没有时间执行这个功能?
  • 不,这对我没有帮助。我认为存在异步 React 问题
  • 非常适合我!非常感谢!正是我想要的! :)
猜你喜欢
  • 2017-10-17
  • 2022-01-17
  • 2022-12-11
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 2016-08-22
相关资源
最近更新 更多