react setState 未更新 class 组件中的状态

react setState is not updating state in class component

为什么 react setState 没有更新我代码中 class 组件的状态

在控制台中,显示了我的数据 (console.log(data))

但是 setState 没有更新状态

有什么问题

export default class Posts extends Component {
    constructor(props) {
        super(props)
        this.state = {
            posts: null,
            isPending: true
        }
    }

    componentDidMount() {
        fetch('http://localhost:5000/api/all_posts/')
            .then(response => response.json())
            .then(data => {
                console.log(data)
                this.setState({ posts: data });
            })
    }
    render() {
        return (
            <div className="posts">
                {this.isPending && <div>loading...</div>}
                {this.state.posts && this.state.posts.map((post) => {
                    <div className="post" key={post.id}>
                        {post.slug}
                    </div>
                })}
            </div>
        )
    }
}

你输入 this.isPending 而不是 this.state.isPending

你有 3 个错误。

  1. 您正在检查 this.isPending 而不是 this.state.isPending
  2. 您的地图函数没有 returning 任何东西。每当您使用大括号 ({}) 时,您都需要添加 return 关键字。如果你不使用大括号,你应该使用一个隐式的 return,这是通过在你的 returned object/component 周围使用括号来完成的。所以改成这样...
render() {
        return (
            <div className="posts">
                {this.state.isPending && <div>loading...</div>}
                {this.state.posts && this.state.posts.map((post) => (
                    <div className="post" key={post.id}>
                        {post.slug}
                    </div>
                ))}
            </div>
        )
    }
  1. 最后,当您在 componentDidMount 中设置 API 调用后的帖子值时,您应该将 isPending 设置为 false。所以像这样...
  componentDidMount() {
    fetch("/api/all_posts/")
      .then((response) => response.json())
      .then((data) => {
        this.setState({ posts: data, isPending: false });
      });
  }