简体   繁体   English

无法设置 state REACT/JS:无法读取未定义的属性“地图”

[英]Fail to set state REACT/JS: Cannot read property 'map' of undefined

Hello I am trying to loop through a list object and render an object with each entry of the list.您好,我正在尝试遍历列表 object 并使用列表的每个条目呈现 object。 However, I kept running into the same error.. I am also wondering how can I see if I a setting the state correctly?但是,我一直遇到同样的错误。我还想知道如何查看我是否正确设置了 state?

Here is the error that I get这是我得到的错误

Uncaught TypeError: Cannot read property 'map' of undefined
    at Feed.render (bundle.js:11417)
    at finishClassComponent (bundle.js:7881)
    at updateClassComponent (bundle.js:7878)
    at beginWork (bundle.js:7974)
    at performUnitOfWork (bundle.js:8294)
    at workLoop (bundle.js:8318)
    at HTMLUnknownElement.callCallback (bundle.js:6296)
    at Object.invokeGuardedCallbackDev (bundle.js:6312)
    at invokeGuardedCallback (bundle.js:6251)
    at performWork (bundle.js:8354)

Here is my json on API:这是我在 API 上的 json:

{
  "next": "", 
  "posts": [
    {
      "postid": 3, 
      "url": "/api/v1/p/3/"
    }, 
    {
      "postid": 2, 
      "url": "/api/v1/p/2/"
    }, 
    {
      "postid": 1, 
      "url": "/api/v1/p/1/"
    }
  ], 
  "url": "/api/v1/p/"
}

Here is my obj class:这是我的 obj class:

constructor(props) {
    // Initialize mutable state
    super(props);
    this.state = { posts: []};
  }


  componentDidMount() {
    // Call REST API to get number of likes
    fetch(this.props.url, { credentials: 'same-origin' })
    .then((response) => {
      if (!response.ok) throw Error(response.statusText);
      return response.json();
    })
    .then((data) => {
      this.setState({
        posts: data.posts,
      });
    })
    .catch(error => console.log(error));
  }

  render() {
    const nums = [1,2,3,4,5,6]
    var newData = Array.from(this.state.posts)


    return (
      <ul> 
        {this.state.newData.map((post)=> (
          <li>post</li>
        ))}
      </ul>
    );
  }
}

You do not have newData stored in your component's state object.您的组件的newData object 中没有存储 newData。

newData is scoped locally to the render() method. newData在本地限定为render()方法。

This should be solved by simply replacing this.state.newData.map(...) with newData.map(...)这应该通过简单地将this.state.newData.map(...)替换为 newData.map(... newData.map(...)来解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM