在调用 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 });
};
所以页面第一次渲染时没有questionsAsnwers
,当我得到questionAnswers
时页面被重新渲染
是否有更好的解决方案来避免重新渲染?
最佳答案
根据 React 文档,处理 API 调用的最佳方法是在 componentDidMount
方法 react lifeCycle 中。此时你所能做的就是添加一个微调器,让你的组件更加人性化。
希望在下一个 React 版本中。 React 将引入一种新的方法来使用 suspense
方法解决此类问题 https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6
关于javascript - 用 React 调用 API 的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751618/