【问题标题】:I receive an error when attempting to .map through an array from an api尝试通过 api 中的数组进行 .map 时收到错误消息
【发布时间】:2020-08-08 15:26:50
【问题描述】:

我目前正在尝试遍历从 api 获得的数组。

我当前的代码是:

displayEmailList = () => {
    let emails = [...this.state.info.emails]

    return emails.map(email => {
      console.log(email)
    })
  }

这是我的状态和异步函数:

state = {
        info: '',
        domain: 'homeadvisor.com'
    };

    async componentDidMount() {
        let info = await axios.get(
            `https://api.hunter.io/v2/domain-search?domain=${this.state
                .domain}&api_key=76056a7300959044150346f9d8dd3c5d6faef844`
        );

        this.setState({
            info: info.data.data
        });
    }

我收到的错误信息是:

TypeError: this.state.info.emails is not iterable

但是,如果我 console.log(this.state.info)

我可以清楚地看到我有一系列电子邮件

【问题讨论】:

  • 可能 map 语句在 API fetch 之前运行。
  • 用回复更新问题

标签: javascript arrays reactjs axios


【解决方案1】:

state 中的 info 初始值是一个空字符串。

像这样初始化你的状态:

state = {
    info: {email: []},
    domain: 'homeadvisor.com'
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多