繁体   English   中英

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

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

您好,我正在尝试遍历列表 object 并使用列表的每个条目呈现 object。 但是,我一直遇到同样的错误。我还想知道如何查看我是否正确设置了 state?

这是我得到的错误

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)

这是我在 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/"
}

这是我的 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>
    );
  }
}

您的组件的newData object 中没有存储 newData。

newData在本地限定为render()方法。

这应该通过简单地将this.state.newData.map(...)替换为 newData.map(... newData.map(...)来解决

暂无
暂无

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

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