【问题标题】:How can i pause a function till a response comes back and state is set我如何暂停功能直到响应返回并设置状态
【发布时间】:2019-05-23 02:50:12
【问题描述】:

我正在运行一个函数,该函数有一个 API 调用,它返回一个我用来设置状态的响应,然后触发另一个使用刚刚更新的状态的函数。第二个函数在响应返回并更新状态之前运行的问题

我试过了。然后我认为应该可以工作

import React from "react";
import API from "../../utils/API"
class Content extends React.Component {
    state={
        postID:"",
        statusPost:""
    }

    submitPost = () => {
        API.savePost({
            content: this.state.statusPost,
            post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
        })
        .then(console.log(this.submitPost))
        .then(res => {

            this.setState({ postID:res.data._id })

            console.log(this.state)
        })
            .then(this.addPostID())
            .catch(err => console.log(err));

    }


    addPostID = () => {

    API.postID({
        _id:  this.props.userInfo.user_ID,
        post:this.state.postID
      })

      .then(res => console.log(res))
      .catch(err => console.log(err));

    }
}

【问题讨论】:

    标签: reactjs api promise pause


    【解决方案1】:

    这里的问题是setState 本身就是asynchronious。它更好地用于基于状态更改渲染 React 组件,而不是在函数调用之间传输数据。所以最好用这种方式重构你的代码

    submitPost = () => {
        API.savePost({
            content: this.state.statusPost,
            post_by: this.props.userInfo.firstname + this.props.userInfo.lastname
        })
        .then(console.log(this.submitPost))
        .then(res => {
    
            this.setState({ postID:res.data._id })
    
            console.log(this.state)
            this.addPostID(res.data._id); // As state will not be updated on this point
        })
            .catch(err => console.log(err));
    }
    
    addPostID = (postID) => {
    
    API.postID({
        _id:  this.props.userInfo.user_ID,
        post:postID // Use argument and not state here
      })
    
      .then(res => console.log(res))
      .catch(err => console.log(err));
    
    }
    

    解决这个问题的另一种方法是使用setState 函数的第二个参数,它是状态更新后将被调用的回调。

    例如

    this.setState({ postID:res.data._id }, () => this.addPostID()); // Now addPostId will be called after state updated
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2012-08-21
      相关资源
      最近更新 更多