Подтвердить что ты не робот

Как настроитьState для новых данных в реакции?

Я только начал смотреть на responsejs и пытаться получить данные из API:

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

    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(response => {
            nextProps= response;
        });
  }

Когда обещание возвращает данные, я хочу присвоить их состоянию:

componentWillReceiveProps(nextProps){
    this.setState({data: nextProps})
  }

Как я могу обновить состояние с данными, полученными от API? На данный момент состояние не установлено?

jsbin ref: https://jsbin.com/tizalu/edit?js,console,output

4b9b3361

Ответ 1

Соглашение состоит в том, чтобы сделать вызов AJAX в методе жизненного цикла componentDidMount. Взгляните на документы React: https://facebook.github.io/react/tips/initial-ajax.html

Загрузить начальные данные через AJAX
Получить данные в компонентеDidMount. Когда приходит ответ, храните данные в состоянии, вызывая рендер обновите свой интерфейс.

Таким образом, ваш код будет выглядеть следующим образом: 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'));

Вот еще одно демо (http://codepen.io/PiotrBerebecki/pen/dpVXyb), показывающее два способа достижения этого, используя 1) jQuery и 2) библиотеки Axios.

Полный код:

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')
);

Ответ 2

Вы можете попробовать с приведенным ниже примером кода и сообщить мне, нужна ли вам дополнительная помощь в этом.

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 ();
  }
});

Спасибо!