How to setState to new data in react?

后端 未结 2 2048
闹比i
闹比i 2021-02-07 21:46

I just started looking at reactjs and trying to retrieve data from an API:

constructor(){
    super();
    this.state = {data: false}
    this.nextProps ={};

           


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 22:13

    You can try with below example code and let me know if you needed any further help in this.

    var YourComponentName = React.createClass({
      componentDidMount: function() {
        var that = this;
        // Your API would be calling here and get response and set state here as below example
        // Just an example here with AJAX something you can do that.
        $.ajax({
          url: 'YOURURL',
          dataType: 'json',
          type: 'POST',
          data: data,
          success: function(response) {
            that.setState({data: response})
          }
        });
      },
      render: function() {
        return ();
      }
    });
    

    Thanks!

提交回复
热议问题