【问题标题】:Cannot read property 'posts' of null无法读取 null 的属性“帖子”
【发布时间】:2021-03-12 08:27:24
【问题描述】:

我试图在渲染部分获取 this.state.posts,但它抛出错误 Cannot read property 'posts' of null 知道我做错了什么吗?

class Blog extends React.PureComponent {
  componentDidMount() {
    axios
      .get(
        "http://public-api.wordpress.com/rest/v1/sites/emma.wordpress.com/posts"
      )
      .then((res) => {
        this.setState({ posts: res.data.posts });
        console.log("setState: ", this.state.posts);
      })
      .catch((error) => console.log(error));
  }

  render() {
    return (
      <Wrapper>
        <ul>
          {Object.values(this.state.posts).map((post) => {
            return <li>{post.name}</li>;
          })}
          ;
        </ul>
      </Wrapper>
    );
  }
}

export default Blog;

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    你的代码中没有定义state,请像这样定义

    class Blog extends React.PureComponent {
    
      state = {posts: []};
    
      componentDidMount() {...}
    
      render() {
        return (...);
      }
    }
    
    export default Blog;
    

    【讨论】:

      【解决方案2】:

      fetch/axios 函数需要时间。 所以基本上你会尝试映射尚不存在的帖子。

      class Blog extends React.PureComponent {
      constructor(){
      this.state = {
      posts: []
      }
      }
        componentDidMount() {
          axios
            .get(
              "http://public-api.wordpress.com/rest/v1/sites/emma.wordpress.com/posts"
            )
            .then((res) => {
              this.setState({ posts: res.data.posts });
              console.log("setState: ", this.state.posts);
            })
            .catch((error) => console.log(error));
        }
      
        render() {
          return (
            <Wrapper>
              <ul>
                {Object.values(this.state.posts).map((post) => {
                  return <li>{post.name}</li>;
                })}
                ;
              </ul>
            </Wrapper>
          );
        }
      }
      
      export default Blog;

      现在,您将映射一个空数组,直到您将一些值放在那里。 编码愉快!

      【讨论】:

        【解决方案3】:

        您必须先定义posts 状态。在 React 中安装组件时

        1. 状态已初始化,
        2. 然后 DOM 打印出来
        3. 然后生命周期挂钩运行
        4. 然后更新状态
        5. DOM 更新为最新状态

        在您的代码中,您没有定义状态。这就是您收到错误消息的原因。

        【讨论】:

          猜你喜欢
          • 2016-07-23
          • 2018-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多