【问题标题】:React - prevent lifecycle components from rendering the same data twice: WillReceiveProps & componentDidMountReact - 防止生命周期组件两次渲染相同的数据:WillReceiveProps & componentDidMount
【发布时间】:2017-03-09 08:54:40
【问题描述】:

专门针对组件的快速反应问题。我正在使用两种生命周期方法:

  • 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
   }

【问题讨论】:

  • 你的问题措辞奇怪。如果你想保证fetchTest只被调用一次,那么就不要包含componentWillReceiveProps..但是如果你想保持在新params时调用fetchTest的行为,比较this.props.params和@ 987654327@查看id是否不同

标签: javascript reactjs redux


【解决方案1】:

你可能想做

componentWillReceiveProps(nextProps) {
  if (nextProps.params.id !== this.props.params.id) {
    fetchTest(nextProps.params.id);
  }
}

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2020-09-05
    • 2019-05-26
    • 2018-06-17
    • 2020-03-15
    • 2016-11-18
    相关资源
    最近更新 更多