javascript - 类型错误 : Cannot read property 'url' of undefined for JSONPlaceholder

标签 javascript json reactjs react-redux react-router

我正在尝试从 jsonPlaceholder 加载图片。当我console.log出图像数组时,它工作成功。当我尝试从元素调用 URL 时,它会抛出 TypeError。我尝试以异步方式做到这一点,即使这不起作用。有什么解决方法吗?可能是什么问题?

import React, {Component} from 'react';
import axios from 'axios';

class Home extends Component{



    state = {
                posts : [],
                images : []

            };

    componentDidMount =  async () => {
        const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
            this.setState({posts: res.data.slice(0,10)})

        const res2 = await axios.get('https://jsonplaceholder.typicode.com/photos');
            this.setState({images: res2.data.slice(0,10)})

        }


    render = () => {    


        const {posts} = this.state.posts;
        const {images} = this.state.images;

        const PostList = this.state.posts.length ? (


            this.state.posts.map((post,index) => {
                return(
                    <div className = "post card" key = {post.id}>
                            <div className = "card-content">
                                <div className = "card-title">
                                    {post.title}
                                </div>
                                <div className>
                                    {(this.state.images[index].url)} //console.log(this.state.images[index] works, but .URL doesn't 
                                </div>
                                <div>
                                    <p>{post.body}</p>
                                </div>
                            </div>
                    </div>

                )
            })) : (<div className = "center">No Posts!</div> ) 

        return(
                <div className = "container">
                    <div className = "center">
                        {PostList}
                    </div>
                </div>)
    }

}

export default Home;

最佳答案

问题出现在多个 setState 中。一旦你设置了State,它就会异步更新和渲染。所以没有等待next setState。最好在一次调用中设置这两个数据。

componentDidMount =  async () => {
        const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
            this.setState({posts: res.data.slice(0,10)})

        const res2 = await axios.get('https://jsonplaceholder.typicode.com/photos');
            this.setState({images: res2.data.slice(0,10)})

        }

您可以像这样清理代码:

工作岗位: https://codesandbox.io/s/articlepodcast-wd2rv?file=/home.js:0-1214

import React, { Component } from "react";
import axios from "axios";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      images: []
    };
  }

  componentDidMount = async () => {
    const res = await axios.get("https://jsonplaceholder.typicode.com/posts");
    const res2 = await axios.get("https://jsonplaceholder.typicode.com/photos");
    this.setState({
      posts: res.data.slice(0, 10),
      images: res2.data.slice(0, 10)
    });
  };

  render = () => {
    const { posts, images } = this.state;
    const PostList = posts.length ? (
      posts.map((post, index) => {
        return (
          <div className="post card" key={post.id}>
            <div className="card-content">
              <div className="card-title">{post.title}</div>
              <div className>{images[index].url} </div>
              <div>
                <p>{post.body}</p>
              </div>
            </div>
          </div>
        );
      })
    ) : (
      <div className="center">No Posts!</div>
    );

    return (
      <div className="container">
        <div className="center">{PostList}</div>
      </div>
    );
  };
}

export default Home;

关于javascript - 类型错误 : Cannot read property 'url' of undefined for JSONPlaceholder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61167433/

相关文章:

javascript - 在 Ember 时间轴上动态加载/重新加载绑定(bind)数据

javascript - javascript中忽略字符串的正则表达式

jquery - 有没有办法在 jqgrid treeGrid url 请求中传回附加数据?

javascript - axios.post().then() 没有将已解析的数据传递给回调函数

reactjs - 根据状态变化进行查询

javascript - 如何使用原型(prototype)获取背景图像的 x 或 y 位置?

javascript - react 路由器 : reset focus on route change (accessibility)

php - 使用 UTF-8 将 PHP 数组转换为 JSON 对象

asp.net - 如何接收 JSON 作为 MVC 5 操作方法参数

javascript - 如何在 stackNavigator react 导航内的屏幕中隐藏底部栏