【问题标题】:Sending a post request to jsonplaceholder fails in React Redux在 React Redux 中向 jsonplaceholder 发送 post 请求失败
【发布时间】:2021-02-01 10:01:06
【问题描述】:

我制作了一个简单的 React Redux 应用程序,它从 jsonplaceholder 获取帖子列表,其中包含一个允许用户发送 POST 请求的表单。当我根据 Redux DevTools 扩展发送一个帖子请求时,它被成功添加标记为帖子编号 101。这是它的快照

但问题是在单击提交按钮 3 次后它显示在屏幕上。

前两次点击既不显示标题也不显示正文,但在第三次点击时开始显示。 这是Posts.jsx 文件,这是我在发布请求后使用componentDidUpdate 更新组件的方式。

class Posts extends Component {
    componentDidMount(){
        this.props.fetchPosts();
    }

    componentDidUpdate(nextProps) {
        if (nextProps.newPost) {
            this.props.posts.unshift(nextProps.newPost);
        }
    }
    
    renderPosts(){ // cutted for brevity  }

    render() {
        return (
            {this.renderPosts()}
        )
    }
}

const mapStateToProps = (state) => {
    return {
        posts: state.posts.items,
        newPost: state.posts.item,
    }
}


export default connect(mapStateToProps, { fetchPosts })(Posts);

Here is its GitHub link repository。 我得到的唯一错误是以下错误。

index.js:1 Warning: Each child in a list should have a unique "key" prop.

我不认为这与渲染新帖子有任何关系,但我已经在循环组件时指定了一个“键”。

在这个帖子请求过程中我做错了什么?谢谢。

【问题讨论】:

    标签: javascript reactjs api http-post jsonplaceholder


    【解决方案1】:

    您使用了错误的生命周期方法。为了获得nexProps,您必须使用componentWillReceiveProps 而不是componentDidUpdate。

    componentDidUpdate 会给你之前的 Props 和之前的 State。

    
      componentWillReceiveProps(nextProps) {
        if (nextProps.newPost) {
          this.props.posts.unshift(nextProps.newPost);
        }
      }
    
    

    上面的 sn-p 应该可以工作。

    但这种方法已被弃用。 react 引入了一种替代方法(一种)。这称为getDerivedStateFromProps。问题是它是一个静态方法,你不能在这个方法中访问以前的道具(this.props)。

    如果你需要它,你做错了什么,因为它是一种反模式。

    【讨论】:

    • 是的,谢谢您的评论。现在不是很不安全吗?在 React 文档中,据说这个生命周期是不安全的,应该不惜一切代价避免。 reactjs.org/docs/react-component.html#updating
    • 是的,它已被弃用。您可以尝试static getDerivedStateFromProps(nextProps, prevState)了解详情,请查看:stackoverflow.com/questions/50692160/…
    • 我很困惑 React 推荐 componentDidUpdate 而不是 getDerivedStateFromProps。请更新您的答案。
    • 感谢您更新答案。问题是我无法在这个静态方法中访问this。有什么解决办法吗? POST 请求后如何更新组件?
    猜你喜欢
    • 2020-04-06
    • 2019-09-23
    • 1970-01-01
    • 2019-07-10
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多