reactjs - 当组件 props 改变时获取新数据

标签 reactjs

我有 4 个按钮,单击按钮后会调用一个组件,根据单击的按钮显示不同的数据。

当我第一次单击按钮时,该组件的构造函数和 componentWillMount() 函数被调用,但之后,直到我刷新页面或导航到不同页面并返回时才调用它.

那么,有没有办法在每次调用特定组件时调用组件的 componentWillMount() 函数或构造函数?

我没有附加代码,因为问题非常简单。

最佳答案

看起来您正在向组件提供不同的 Prop ,因此您需要将 componentWillReceivePropscomponentDidMount 一起使用

根据文档

componentWillReceiveProps(nextProps)

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

因此,您需要更新检查子组件中的 props 是否已更改 componentWillReceiveProps 并根据它采取行动。由于第一次安装组件时不会调用 componentWillReceiveProps ,因此您还需要使用 componentDidMount 因为它仅在第一次渲染时调用

关于reactjs - 当组件 props 改变时获取新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445460/

相关文章:

javascript - 使用 lodash 对数组对象与日期进行排序

reactjs - React警告: Each child in an array or iterator should have a unique "key" prop.检查 `App`的渲染方法

javascript - 如何突出显示字符串中的文本?

node.js - 使用 Superagent 服务器端获取连接 ECONNREFUSED 错误

javascript - react native : How to reference current route in Navigator's navigationBar={}?

javascript - 减少脉轮表中列之间的空白

reactjs - 在 react js 中的函数组件中传递默认 Prop

node.js - 代理套接字 io 无法与 docker 上的 nginx、node 连接

javascript - 如何让我的 reducer 更新状态中对象的一个​​属性?

javascript - 使用 apollo-boost 持久缓存