简体   繁体   English

如何定位通过axios.get请求创建的数组中的元素?

[英]How do I target a element in an array made through an axios.get request?

Im trying to create a label that will display a status that changes over time. 我正在尝试创建一个标签,该标签将显示随时间变化的状态。 I have a database that has all the statuses, its just a matter of creating a react component that will output the status. 我有一个具有所有状态的数据库,只需要创建一个将输出状态的React组件即可。 I just need to output one and Im trying to do that by targeting the specific portion in an array, but it's giving me a the following error: 我只需要输出一个,而林正试图通过针对数组中的特定部分来做到这一点,但这给了我以下错误:

Cannot read property 'name' of undefined 无法读取未定义的属性“名称”

class App extends React.Component {
  state = {
    drought_status: [],
    drought_id: 0
  };

  componentDidMount() {
    axios.get("https://jsonplaceholder.typicode.com/users").then(res => {
      console.log(res);

      this.setState({ drought_status: res.data });
    });
  }

  render() {
    return (
      <div>
        <UncontrolledDropdown>
          <DropdownToggle caret>Dropdown</DropdownToggle>

          <DropdownMenu>
            <DropdownItem>{this.state.drought_status[0].name}</DropdownItem>
          </DropdownMenu>
        </UncontrolledDropdown>
      </div>
    );
  }
}

Your drought_status array is empty before your request is complete, so this.state.drought_status[0] will be undefined , and trying to access name on that will give rise to your error. 在您的请求完成之前您的drought_status数组为空,因此this.state.drought_status[0]将是undefined ,并且尝试访问该name将引发错误。

You could check that this.state.drought_status[0] is set before you try to access name . 您可以在尝试访问name之前检查this.state.drought_status[0]是否已设置。

Example

render() {
  const firstDroughtStatus = this.state.drought_status[0];

  return (
    <div>
      <UncontrolledDropdown>
        <DropdownToggle caret>Dropdown</DropdownToggle>
        <DropdownMenu>
          {firstDroughtStatus ? (
            <DropdownItem>{firstDroughtStatus.name}</DropdownItem>
          ) : null}
        </DropdownMenu>
      </UncontrolledDropdown>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM