此文章是翻译AJAX and APIs这篇React(版本v16.2.0)官方文档。

AJAX and APIs

我如何使用AJAX 请求

在React 中你可以使用任何你喜欢的AJAX 库。像很常用的AxiosjQuery AJAX,以及浏览器内置的window.fetch

我应该在组件的哪个生命周期中使用AJAX 请求

你应该在componentDidMount 生命周期方法中设置通过AJAX 请求到的数据。这样你可以使用setState 去更新你的组件,当数据被检索到的时候。

例子:使用AJAX 结果去设置local state

下面这个例子展示了在componentDidMount 中使用AJAX 请求去设置组件的local state。

例子中的API 返回如下格式的JSON 对象

  1. {
  2. items: [
  3. { id: 1, name: 'Apples', price: '$2' },
  4. { id: 2, name: 'Peaches', price: '$5' }
  5. ]
  6. }
  1. class MyComponent extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. error: null,
  6. isLoaded: false,
  7. items: []
  8. };
  9. }
  10. componentDidMount() {
  11. fetch("https://api.example.com/items")
  12. .then(res => res.json)
  13. .then(
  14. (result) => {
  15. this.setState({
  16. isLoaded: true,
  17. items: result.items
  18. });
  19. },
  20. // Note: it's important to handle erros here
  21. // instead of a catch() block so that we don't swallow
  22. // exceptions from actual bugs in component.
  23. (error) => {
  24. this.setState({
  25. isLoaded: true,
  26. error
  27. });
  28. }
  29. )
  30. }
  31. render() {
  32. const { error, isLoaded, items } = this.state;
  33. if (error) {
  34. return <div>Error: {error.message} </div>
  35. } else if (!isLoaded) {
  36. return <div>Loading...</div>
  37. } else {
  38. return (
  39. <ul>
  40. {items.map(item => (
  41. <li key={item.name}>
  42. {item.name} {item.price}
  43. </li>
  44. ))}
  45. </ul>
  46. );
  47. }
  48. }
  49. }

取消

注意如果在一个AJAX 请求完成之后将组件卸载,你可能会看到cannot read property 'setState' of undefined 警告。如果这是一个问题,你可以追踪AJAX 请求并在componentWillUnmount 生命周期方法中取消它。