【问题标题】:render order issue (React)渲染顺序问题(反应)
【发布时间】:2018-12-19 08:38:05
【问题描述】:

我有一个 Paypal 组件,它在成功付款时执行逻辑。

目标是首先执行paypal/axios.post,然后是this.setState(...)

以下代码块执行setState() Paypal 逻辑之前,并且没有付款:

render() {
    const onSuccess = payment => {
      axios
        .post(
          "http://compute.amazonaws.com:3000/ethhash",
          {userInput: this.props.userInput}
        )
        .then(response => console.log(response.data, payment))
            .catch(function(error) {
          console.log(error);
        });
    };

this.setState({ redirect: true });

if (this.state.redirect) {
      return <Redirect to="/FinishedPaying" userInput={this.state.userInput} />;
    }}

如果我将 setState() 嵌套在 onSuccessaxios.post 逻辑中,它会破坏我的 (express) 服务器。奇怪的是,我的服务器给我的错误是某个函数不是函数……命名函数在所有其他条件下都有效。

感谢您对我的帮助,干杯:)

【问题讨论】:

  • 不要在渲染中使用setState。也不应该在渲染中触发请求
  • 嗯,谢谢您的反馈。 setState 应该在哪里呈现?当您说“请求”时,您是在谈论axios.post 逻辑吗?
  • setState 可以在生命周期方法或任何事件处理程序方法中调用。是的,我的意思是“请求”-> axios.post 在你的情况下。
  • setState 如果你在 render 中使用它会调用 render 并且 setState 会再次调用 render 所以它会无限循环

标签: reactjs paypal render setstate


【解决方案1】:

首先,您不应该在渲染函数中使用 setState,您必须将其移至 React 的其他生命周期,或者您需要根据某些用户操作调用 post 请求。

onPayment= async ()=>{
 const res=await axios.post("http://compute.amazonaws.com:3000/ethhash",
          {userInput: this.props.userInput}
        )
   // check here if any error if error don't set the setState.

 this.setState({redirect:true})
}

【讨论】:

  • 在我的代码中,如果 Paypal 返回成功付款,.post 将激活。这不是用户操作吗?如果我将 setState 放入 componentDidMount() 我有同样的问题......重定向发生在 Paypal 逻辑可以执行之前。感谢您的反馈,我会根据您的建议尝试一些事情。
  • @HanleySoilsmith:不如试试componentWillReceivedProps生命周期方法
  • 我不熟悉,会做一些研究。如果我删除了所有的 axios 逻辑,它会很好地工作(但我需要在某处使用 axios 逻辑)。我还要看看受保护的路由是否是一个东西,因为我可以将 axios 逻辑放在“/FinishedPaying”页面上。
  • React 文档说 componentWillReceivedProps 是遗留的,应该避免...reactjs.org/docs/react-component.html
  • @HanleySoilsmith:因为您正在进行异步 API 调用,所以它将调用您的 API 并执行下一条语句,因此您应该等待它或实现承诺,然后您编写 setState 一次你得到了服务器的响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 2016-07-13
  • 2021-04-13
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多