Ответ 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')
);