我有 4 个按钮,单击按钮后会调用一个组件,根据单击的按钮显示不同的数据。
当我第一次单击按钮时,该组件的构造函数和 componentWillMount()
函数被调用,但之后,直到我刷新页面或导航到不同页面并返回时才调用它.
那么,有没有办法在每次调用特定组件时调用组件的 componentWillMount()
函数或构造函数?
我没有附加代码,因为问题非常简单。
最佳答案
看起来您正在向组件提供不同的 Prop ,因此您需要将 componentWillReceiveProps
与 componentDidMount
一起使用
根据文档
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 comparethis.props
andnextProps
and perform state transitions usingthis.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/