首页 > 解决方案 > 如何修复 typeError:无法读取未定义的属性“地图”

问题描述

我想从 Json Server 获取数据,我需要在哪里编辑?

这是我得到的错误

“TypeError:无法读取未定义的属性‘地图’”

getPosts() {
    axios.get("http://localhost:8001/employees")
    .then(response => {
        this.setState({
            posts : response.data.posts,
            isLoading: false
        });
    })

    .catch(error => this.setState({error, isLoading : false}));
}

componentDidMount () {
    this.getPosts();
}

render() {
  const {isLoading , posts} = this.state;
  return (
    <React.Fragment>
        <h2>Data JSON</h2>
        <div>
            {!isLoading ? (
                posts.map(post => {
                    const {id, first_name, last_name, email} = post;
                    return (
                        <div>
                            <h2>{id}</h2>
                            <h2>{first_name}</h2>
                            <p>{last_name}</p>
                            <p>{email}</p>
                            <hr />
                        </div>
                    );
                })
            ) : (
                <p>Loading...</p>
            )}
        </div>
    </React.Fragment>
  );
}

}

导出默认登录;

我希望出现来自 json 服务器的数据,但不是

标签: reactjs

解决方案


将帖子的默认状态设置为数组,并将 if 语句添加到您的渲染函数以检查该组件是否应该渲染帖子。

class YourClassName extends React.Component {
  state = {
    posts: [],
  }

  getPosts() {
    axios.get("http://localhost:8001/employees")
    .then(response => {
        this.setState({
            posts : Array.isArray(response.data) ? response.data : response.data.posts,
            isLoading: false
        });
    })
    .catch(error => this.setState({error, isLoading : false}));
  }

  componentDidMount () {
    this.getPosts();
  }

  render() {
    <>
      {posts.length > 0 && posts.map(post => <p>{post}</p>)}
    </>
  }
}

推荐阅读