当 React 组件 prop 更改时如何获取数据?

IT技术 javascript reactjs react-router
2021-03-27 11:54:54

我的 TranslationDetail 组件在打开时传递一个 id,并基于此在类构造函数中触发外部 api 调用,将数据接收到状态,并将此数据显示在 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 调用。

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

4个回答

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

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

componentDidUpdate如果你关心的特定 props 没有改变,请确保将 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);
   }
}
谢谢,使用这些事件它现在可以正常工作。
2021-06-12 11:54:54
注意:我编辑了答案,因为它不必要地复杂。将状态同步到 props通常是一个坏主意,在这种情况下你应该只使用 props。
2021-06-14 11:54:54
如果在获取数据后想要更新状态怎么办?我们可以在 componentdidupdate 本身或像 getDerivedPropsToState 这样的任何其他建议中做到这一点吗?如果 getDerivedPropsToState 使用,它不会从 componentdidupdate 获取最新的 props。
2021-06-19 11:54:54

从阵营16.3及以后componentWillMountcomponentWillUpdatecomponentWillReceiveProps弃用

您可以使用 staticgetDerivedStateFromProps并根据props的变化返回一个新状态。

您无法像props一样访问您的 this 对象,因此您无法nextProps与当前的propsby进行比较nextProps.sth !== this.props.sth您可以将您的prevStatevalue与nextProps状态进行比较并返回新的value。

确保UNSAFE_您现在添加到当前componentWillMount和其他已弃用的生命周期方法中。

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

您可以查看组件规格和生命周期

方法已弃用
2021-06-06 11:54:54

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