【问题标题】:Return response.data in function inside .then callback | Axios在函数内部返回 response.data .then 回调 |爱讯
【发布时间】:2017-05-28 20:21:04
【问题描述】:

是否可以在.then 回调中返回函数?

我想做这样的事情:

axios.post('url_api/endpoint')
  .then(function(response){

     renderAdmissionReponse(){
       <div>Success response.data</div>
     }

  })

稍后在这样的组件中渲染它:“

<div className="row spacer">
 {this.renderAdmissionReponse()}
</div>

有可能吗?

【问题讨论】:

  • 。由于它的反应,您可以在外部渲染中调用该函数,then 将更新最终更新 UI 的state
  • 好吧,基本上是这样的:axios.post('url_api/endpoint') .then(function(response){ this.setState({ admissionResponse: response.data }) })
  • 是的,admissionResponse 格式是什么?
  • 它是 JSON 格式
  • 它是一个对象内容:为了渲染我这样做了:const admissionResponseJSON = JSON.stringify(this.state.admissionResponse, null, 2)

标签: reactjs redux axios


【解决方案1】:

其实我能理解你的需要,但是你上面的代码是错误的!

你想要的是:使用 axios 成功加载数据后,数据将在页面上正确呈现。如果是这样,您可以使用以下方式:

constructor(props) {
    // ...
    this.state = ({
        admissionResponse: [],
        // your other state variables here
    })
}

renderAdmissionReponse = (data) => {
    this.setState({
        admissionResponse: data,
    });
}

// ... You can put this inside `ComponentDidMount()`, then just call the function to setState with returned data
axios.post('url_api/endpoint')
    .then((response) => {

        this.renderAdmissionReponse(response.data);

    })
// ...

render() {
    return (
        <div className="row spacer">
            <div>{this.state.admissionResponse.authorizationId}</div>
            <div>{this.state.admissionResponse.authorizationNum}</div>
            {this.state.admissionResponse.lineItems.map((line) =>{
              return(
                <div>{line.id}</div>
                <div>{line.lineItemNumber}</div>
              )
            })}  
        </div>
    );
}

还请检查您的 response.data 结构然后检索正确的键,上面的代码我只是试图解释正确的反应如何异步加载数据并在此之后在页面上呈现的方式。如有错误,请在此处发布,谢谢。

【讨论】:

  • 很高兴你已经成功了^^!如有进一步反应的问题,请随时联系我,谢谢!
  • 非常感谢!我会
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 2018-07-09
  • 2019-08-29
  • 2018-08-19
  • 1970-01-01
相关资源
最近更新 更多