专门针对组件的快速 react 问题。我正在使用两种生命周期方法:
- componentDidMount() - 用于在组件首次呈现时检索数据
- componentWillReceiveProps(nextProps) - 用于在某些参数更改时更新数据
这很好用。但是,当我使用组件刷新页面时,两种生命周期方法都会在其中一种方法足够时执行。页面上的数据仍然正确,但似乎效率有点低。如果可能的话,如何将它们结合到生命周期中?
下面的示例将在页面刷新时调用 fetchTest() 两次。如果我删除 componentDidMount,那么如果用户刷新页面,数据最初将不会加载。
关于如何让 fetchTest() 调用一次,无论用户如何访问组件,有什么想法吗?
componentDidMount() {
fetchTest(this.props.params.id);
// for initial component render
}
componentWillReceiveProps(nextProps) {
fetchTest(nextProps.params.id);
// for when (params.id) is changed. data within component is updated
}
最佳答案
你可能想做
componentWillReceiveProps(nextProps) {
if (nextProps.params.id !== this.props.params.id) {
fetchTest(nextProps.params.id);
}
}
关于javascript - React - 防止生命周期组件渲染相同的数据两次 : WillReceiveProps & componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40271622/