How to setState to new data in react?

后端 未结 2 2053
闹比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: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 (
         
    {this.state.data}
    ) } } ReactDOM.render(, 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 (
          

    Time via axios: {this.state.time1}

    Time via jquery: {this.state.time2}

    ); } }; ReactDOM.render( , document.getElementById('content') );

提交回复
热议问题