【问题标题】:How to fix typeError: Cannot read property 'map' of undefined如何修复 typeError:无法读取未定义的属性“地图”
【发布时间】:2019-08-19 17:57:22
【问题描述】:

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

这是我得到的错误

"TypeError: 无法读取未定义的属性 'map'"

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 服务器的数据会出现,但它不会出现

【问题讨论】:

  • 发布完整的组件以及您收到的服务器的响应。您面临的错误意味着您正在尝试从不是 array 的数据中访问属性映射

标签: reactjs


【解决方案1】:
constructor(props) {
   super(props) 
   this.state()={isLoading: true, posts: []}
}
getPosts() {
    axios.get("http://localhost:8001/employees")
    .then(response => {
        var posts = [];
        if(response.data.posts.length > 0) {
          posts = response.data.posts
        }
        this.setState({isLoading: false, posts: posts})   
     })

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

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>
  );
}

【讨论】:

  • 我之前已经做过了。类登录扩展 React.Component { state = { posts: [], isLoading: true, errors: null };
    中的错误。我想从 json 31 获取数据表 | return ( 32 | 33 |

    数据 JSON

    > 34 |
    35 | ^ 36 |{!isLoading ? ( 37 |posts.map(post => { (匿名函数) C:/Users/fernando.siregar/project/my-app/src/login.js:14 11 |getPosts(){ 12 |axios.get("localhost:8001/employees") 13 |then(response =>{ > 14 | this.setState({ 15 | ^ 16 |posts : response.data.posts, 17 |isLoading: false
【解决方案2】:

该错误表明您正在尝试在 posts 存在之前对其进行映射。

如果你还没有在constructor中设置isLoading,则需要在componentDidMount中设置true

componentDidMount () {
    this.setState({isLoading: true})
    this.getPosts();
}

您的catch 块也有问题。

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

你将isLoading设置为false,然后在render方法中,你有这个:

{!isLoading ? (
      posts.map(post => { 
      //....

即使response 中有错误,您也正在尝试呈现帖子。

【讨论】:

  • 我之前已经做过了。类登录扩展 React.Component { state = { posts: [], isLoading: true, errors: null };
    中的错误。我想从 json 31 获取数据表 | return ( 32 | 33 |

    数据 JSON

    > 34 |
    35 | ^ 36 |{!isLoading ? ( 37 |posts.map(post => { (匿名函数) C:/Users/fernando.siregar/project/my-app/src/login.js:14 11 |getPosts(){ 12 |axios.get("localhost:8001/employees") 13 |then(response =>{ > 14 | this.setState({ 15 | ^ 16 |posts : response.data.posts, 17 |isLoading: false
【解决方案3】:

将帖子的默认状态设置为数组,并将 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>)}
    </>
  }
}

【讨论】:

  • 我之前已经做过了。类登录扩展 React.Component { state = { posts: [], isLoading: true, errors: null };
    中的错误。我想从 json 31 获取数据表 | return ( 32 | 33 |

    数据 JSON

    > 34 |
    35 | ^ 36 |{!isLoading ? ( 37 |posts.map(post => { (匿名函数) C:/Users/fernando.siregar/project/my-app/src/login.js:14 11 |getPosts(){ 12 |axios.get("localhost:8001/employees") 13 |then(response =>{ > 14 | this.setState({ 15 | ^ 16 |posts : response.data.posts, 17 |isLoading: false
  • 您确定作为响应您收到数组中的帖子吗?
  • 我想从此链接jsonplaceholder.typicode.com/todos 获取数据,错误出现在
    class login extends React.Component { state = { posts: [], isLoading: true, errors: null } ;
  • 如果我从这个链接 "s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json" 获得,它会成功并且没有错误,但是如果我从另一个链接(如 jsonplaceholder.typicode.com/todos)获得数据,则 div 上的输出错误我不知道.
  • 这两个链接有不同的结构。你想从你的回复中得到posts。在jsonplaceholder.typicode.com/todos 你没有它。 ;)
猜你喜欢
相关资源
最近更新 更多
热门标签