How to setState to new data in react?

后端 未结 2 2047
闹比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!

    0 讨论(0)
  • 2021-02-07 22:34

    The convention is to make an AJAX call in the componentDidMount lifecycle method. Have a look at the React docs: https://facebook.github.io/react/tips/initial-ajax.html

    Load Initial Data via AJAX
    Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

    Your code would therefore become: https://jsbin.com/cijafi/edit?html,js,output

    class App extends React.Component {
      constructor() {
        super();
        this.state = {data: false}
      }
    
      componentDidMount() {
        axios.get('https://jsonplaceholder.typicode.com/posts')
            .then(response => {
                this.setState({data: response.data[0].title})
            });
      }
    
      render() {
        return (
         <div> 
          {this.state.data}
         </div>
        )
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('app'));
    

    Here is another demo (http://codepen.io/PiotrBerebecki/pen/dpVXyb) showing two ways of achieving this using 1) jQuery and 2) Axios libraries.

    Full code:

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          time1: '',
          time2: ''
        };
      }
    
      componentDidMount() {
        axios.get(this.props.url)
          .then(response => {
            this.setState({time1: response.data.time});
          })
          .catch(function (error) {
            console.log(error);
          });
    
        $.get(this.props.url)
          .then(result => {
            this.setState({time2: result.time});
          })
          .catch(error => {
            console.log(error);
          });
      }
    
      render() {
        return (
          <div>
            <p>Time via axios: {this.state.time1}</p>
            <p>Time via jquery: {this.state.time2}</p>
          </div>
        );
      }
    };
    
    
    ReactDOM.render(
      <App url={"http://date.jsontest.com/"} />,  document.getElementById('content')
    );
    
    0 讨论(0)
提交回复
热议问题