使用React调用API的最佳实践是什么?

5

在调用API时,我在React中遇到了一个小问题,因为ComponentWillMount已被弃用。

我尝试了以下方法:

class MyClass extends Component {
  constructor() {
  super();

    this.state = {
      questionsAnswers: [[{ answers: [{ text: '', id: 0 }], title: '', id: 0 }]],

    },
  };
}
componentDidMount() {
   this.getQuestions();
}

getQuestions = async () => {
   let questionsAnswers = await Subscription.getQuestionsAndAnswers();
   questionsAnswers = questionsAnswers.data;
   this.setState({ questionsAnswers });
};

因此,在获取questionAnswers之前,页面首次呈现时不包含questionsAsnwers,当我获取questionAnswers后,页面将重新呈现。

有没有更好的解决方案来避免重新呈现?


React文档建议在componentDidMount中加载它。 https://reactjs.org/docs/react-component.html#componentdidmount另请参见 https://github.com/reactjs/reactjs.org/issues/302 - Subin Sebastian
在这种情况下,首次加载符号并一旦问题加载完成更改状态以显示问题...将获得良好的用户体验。最好使用Redux,它为您提供了更好的处理API调用和数据绑定的方式。 - BEJGAM SHIVA PRASAD
2
我建议在任何React组件方法中不使用async关键字,因为Promises是不可取消的。如果在await期间卸载了组件,则会在未安装的组件上调用this.setState。这就是为什么像Redux这样的存储库的创建; React组件最好完全保持同步。如果您确实向组件添加了async,请在componentDidMount中创建订阅,并在componentWillUnmount中取消订阅,但我建议在React组件方法中完全避免使用async关键字。 - Ross Allen
如果在组件首次渲染时没有数据,则根据此形状化您的组件。请参见:https://stackoverflow.com/questions/49697447/fetch-axios-not-return-data-timely-in-reactjs/49697828#49697828 - devserkan
3个回答

3
处理API调用的最佳方式是根据React文档,使用componentDidMount方法在React生命周期中。此时,您只能添加一个旋转器以使您的组件更加用户友好。
希望在下一次React发布中,React将引入一种新的解决这种问题的方法,使用suspense方法,详情请参考https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6

2

使用继承自 React.Component 的类,可以在 componentDidMount 中实现:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.id}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}

如果您使用带有Hooks的函数组件,应该像这样做:
function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}

示例响应:

{
  "items": [
    { "id": 1, "name": "Apples",  "price": "$2" },
    { "id": 2, "name": "Peaches", "price": "$5" }
  ] 
}

Source:

https://reactjs.org/docs/faq-ajax.html


0

我认为,在那种情况下展示加载动画是可以的。 同时,你也应该检查ajax请求是否失败。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接