【问题标题】:React setstate callback does not work after initial useReact setstate 回调在初始使用后不起作用
【发布时间】:2020-01-16 16:31:27
【问题描述】:

我有一个函数,它在初始化时会采用先前设置的状态,并使用它与 axios 进行 api 调用:

 _onRefresh = () => {
    this.setState({ refreshing: true }, () => {
      axios.get(this.state.currentPath)
        .then(res=>{
          console.log(res.data)
          this.props.loadCards(res.data) 
        })
        this.setState({refreshing: false})
    });
  }

我可以看到承诺从未完成,也没有给出响应。

但是,在页面加载后第一次使用时,该功能可以正常工作;它只是在以后的使用中不起作用。

当get请求不起作用时,我采取了state中存储的路径,在postman中发出请求,并收到了有效的结果。

【问题讨论】:

  • 你是在调用 axios 之后立即执行 this.setState({refreshing: false}),而不是在它完成之后。

标签: reactjs react-native axios react-state-management


【解决方案1】:

试试这个

_onRefresh =async () => {
    this.setState({ refreshing: true }, () => {
   await axios.get(this.state.currentPath) //you might need to handle promises to get this working.
        .then(res=>{
          console.log(res.data)
          this.props.loadCards(res.data) 
        })
        this.setState({refreshing: false})
    });
  }

【讨论】:

【解决方案2】:

您应该取消 finally 块中的刷新

get(...)
.then(...)
.catch(...)
.finally(() => this.setState({refreshing: false}))

【讨论】:

  • 请注意,Promise.prototype.finally 仅在当前浏览器(没有 IE 11 甚至 edge 17)和节点 10.x+ 中可用。
  • 我试过了,但没有用。谢谢您的答复。 @JaredSmith
【解决方案3】:

这能解决问题吗?

_onRefresh = () => {
this.setState({ refreshing: true }, () => {
  axios.get(this.state.currentPath)
    .then(res=>{
      console.log(res.data)
      this.props.loadCards(res.data)
      this.setState({refreshing: false}) // moved this line into the then block
    })    
});

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2020-06-19
    • 2017-06-21
    • 2021-05-09
    • 2020-11-02
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多