【问题标题】:How to fetch data when a React component prop changes?React 组件 prop 更改时如何获取数据?
【发布时间】:2016-12-24 08:26:08
【问题描述】:

我的 TranslationDetail 组件在打开时会传递一个 id,并基于此在类构造函数中触发外部 api 调用,将数据接收到 state,并将此数据显示在 TranslationDetail 上。

//Routing:
<Route path="/translation/:id" component={TranslationDetail}/>

//Class:    
class TranslationDetail extends Component {
  constructor(props){
    super(props);

    this.props.fetchTrans(this.props.params.id);
  }

如果我手动输入网址,这一切都很好。如果我想使用 react-router 例如显示下一个项目,如下面的 url 确实发生了变化,但没有触发 api 调用,数据将保持不变。

<button 
  type="button"
  onClick={() => 
    browserHistory.push(`/translation/${Number(this.props.params.id)+1}`)}>
  Next
</button>

请记住,我完全是初学者。发生这种情况的原因是我相信构造函数只运行一次,因此不会触发进一步的 api 调用。

我该如何解决这个问题? 我是否需要列出道具并在更改时调用函数?如果是,怎么做?

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

构造函数不是进行 API 调用的正确位置。

你需要使用生命周期事件:

确保将 props 与 componentDidUpdate 中的先前 props 进行比较,以避免在您关心的特定 props 没有更改时获取。

class TranslationDetail extends Component {    
   componentDidMount() {
     this.fetchTrans();
   }

   componentDidUpdate(prevProps) {
     if (prevProps.params.id !== this.props.params.id) {
       this.fetchTrans();
     }
   }

   fetchTrans() {
     this.props.fetchTrans(this.props.params.id);
   }
}

【讨论】:

  • 谢谢,使用这些事件现在可以正常工作了。
  • 注意:我编辑了答案,因为它不必要地复杂。 Syncing state to props 通常是个坏主意,在这种情况下,您应该只使用道具。
  • 如果获取数据后想要更新状态怎么办?我们可以在 componentdidupdate 本身或任何其他建议(如 getDerivedPropsToState)中执行此操作吗?如果使用 getDerivedPropsToState,它不会从 componentdidupdate 中获取最新的 props。
【解决方案2】:

从 React 16.3 起,componentWillMountcomponentWillUpdatecomponentWillReceivePropsdeprecated

您可以使用静态getDerivedStateFromProps 并根据道具的更改返回新状态。

您无权访问您的 this 对象(如 props),因此您无法通过 nextProps.sth !== this.props.sthnextProps 与您当前的 props 进行比较。您可以将prevState 值与nextProps 进行比较,并返回新的状态值。

让您将UNSAFE_ 添加到您当前的componentWillMount 和其他已弃用的生命周期方法中。

【讨论】:

    【解决方案3】:

    我会使用渲染方法。如果未加载数据,我将渲染加载器微调器并抛出获取数据的操作。为此,我通常使用商店。一旦 store 有来自 api 的数据,将数据标记为已加载,抛出一个事件并让组件从 store 中获取数据,用您的数据表示替换加载器微调器。

    【讨论】:

      【解决方案4】:

      使用componentWillMount 获取数据并设置状态。 然后使用 componentWillReceiveProps 捕获道具的更新。

      您可以查看Component Specs and Lifecycle

      【讨论】:

      • 方法已弃用
      猜你喜欢
      • 2023-03-28
      • 2017-11-30
      • 2021-12-15
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2016-08-28
      • 2017-11-18
      相关资源
      最近更新 更多