当ajax响应到达并渲染时,onclick准备html?

时间:2016-09-09 10:35:34

标签: javascript ajax reactjs axios

嘿,我是新的反应我的要求是,当用户点击按钮时,ajax get请求被触发到 服务器和基于收到的响应我必须准备html并显示它。 下面是我的代码它不工作..它可以通过使用async: false在jquery中解决但我不必使用它 任何想法如何解决使用axios

import React from "react";
import axios from "axios"

class UserItems extends React.Component {

constructor(props) {
  super(props);
  this.state = {
    useritem: ''
  }
} 

prepareHtmlOnAjaxResponse(){

  var user_item = this.state.useritem
  // html prepation done here
  return preparedHtml;
}


getDatFromServeronclick() {

  // getting user data from server is done in this function 
  // when data is receieved it is stored in a state
    var self = this;
    var promise = axios.get("http://localhost:4000/user/1/items.json")
    promise.then(function (response) {
    self.setState({ useritem: response.data.items })
     self.prepareHtmlOnAjaxResponse()  // prepare html 
    })
console.log("executing first and returning null")
}


render() {
   var result = this.getDatFromServeronclick()  // getting undefined value this has to be called onclick
    return (
       <div> 
        {result}  / result is undefined
      </div>

    );
}


 }

export default UserItems;

1 个答案:

答案 0 :(得分:1)

您必须使用self.setState function代替self.state assignment,否则React不会触发该组件的重新呈现。

var promise = axios.get("http://localhost:4000/user/1/items.json")
    promise.then(function (response) {
    self.setState({ useritems: response.data.items })
})

来自React&#39; documentation

不要直接改变this.state ,因为之后调用setState()可能会替换你所做的突变。把this.state看作是不可变的。

然后在render函数

<button onClick={() => this.getDatFromServeronclick() }> {this.state.useritems.map(user => user.title)} </button>

您可以将user.title替换为keys所拥有的object useritems