-1

我正在再次研究reactjs,在这里遇到问题,我认为这很奇怪..

componentDidMount(){
fetch("https://api.imgflip.com/get_memes")
      .then(response => response.json())
      .then(response =>{
        const {memes} = response.data
        this.setState({allMemeImgs: memes})
      })
      console.log(this.state.allMemeImgs)
}

在我从该 API 获取一些值并存储在状态类型数组中之后,尝试像这样调用数组

{console.log(this.state.allMemeImgs)}

试试 1

{console.log(this.state.allMemeImgs[0])}

试试 2

然后当我需要 url 值时,它会抛出错误

{console.log(this.state.allMemeImgs[0].url)}

尝试 3 和错误

用于响应的控制台日志

4

4 回答 4

0

请验证响应是否为数组。你可以在这里发布一次回复吗?

谢谢

于 2019-01-29T03:01:39.440 回答
0

在您的渲染方法中,您必须在深入了解对象之前检查所有数据是否存在。尝试添加此检查。

if (!response.data) {
  return null;
}

希望有帮助。

于 2019-01-29T03:36:38.007 回答
0

问题是:是在第一次渲染之后componentDidMount运行的生命周期方法。在第一次渲染和获取数据之间,是或或空数组(取决于您如何初始化状态)。allMemeImgsundefinednull

如果您仔细查看前两次尝试的日志,您可能会注意到nullundefined高于您想要的输出。

因此,在渲染它们之前,请始终确保数据不为空。最方便的方法是像这样使用短路评估

condition && renderThisIfTrue
于 2019-01-29T03:58:06.373 回答
0

你做错了,你的数组在模因中,所以,

{console.log(this.state.allMemeImgs.meme[0].url)}

另外,请在获取数据时使用 await ,以便在进一步操作之前等待响应

await fetch("https://api.imgflip.com/get_memes")
      .then(response => response.json())
      .then(response =>{
        const {memes} = response.data
        this.setState({allMemeImgs: memes})
      })
于 2019-01-29T03:59:07.720 回答