Javascript 如何监听 react.js 中的状态变化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26402534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to listen state changes in react.js?
提问by Eniz Gülek
采纳答案by edoloughlin
I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:
我没有使用过 Angular,但是阅读上面的链接,您似乎正在尝试为不需要处理的东西编写代码。您在 React 组件层次结构中更改状态(通过 this.setState()),React 将导致您的组件重新渲染(有效地“监听”更改)。如果您想从层次结构中的另一个组件“收听”,那么您有两个选择:
- Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
- Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor pluginis very useful for managing this.
回答by Derek Slager
The following lifecycle methodswill be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.
当状态改变时将调用以下生命周期方法。您可以使用提供的参数和当前状态来确定是否发生了有意义的更改。
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
回答by hasain
I think you should be using below Component Lifecycle as if you have an input property which on update needs to trigger your component update then this is the best place to do it as its will be called before render you even can do update component state to be reflected on the view.
我认为您应该在组件生命周期下方使用,就好像您有一个输入属性在更新时需要触发您的组件更新那么这是最好的地方,因为它将在渲染之前被调用,您甚至可以将组件状态更新为反映在视图上。
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
回答by Aprillion
Since React 16.8 in 2019 with useStateand useEffectHooks, following are now equivalent (in simple cases):
自 2019 年的 React 16.8 使用useState和useEffectHooks以来,以下现在是等效的(在简单情况下):
AngularJS:
AngularJS:
$scope.name = 'misko'
$scope.$watch('name', getSearchResults)
<input ng-model="name" />
React:
反应:
const [name, setName] = useState('misko')
useEffect(getSearchResults, [name])
<input value={name} onChange={e => setName(e.target.value)} />
回答by Shivang Gupta
Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy
如上所述使用 useState 和 useEffect 是绝对正确的方法。但是如果 getSearchResults 函数返回订阅,那么 useEffect 应该返回一个函数,该函数将负责取消订阅订阅。useEffect 返回的函数将在每次更改依赖项之前运行(上述情况中的名称)和组件销毁
回答by Malvinka
It's been a while but for future reference: the method shouldComponentUpdate() can be used.
已经有一段时间了,但为了将来参考:可以使用方法 shouldComponentUpdate() 。
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
更新可能由道具或状态的更改引起。当重新渲染组件时,这些方法按以下顺序调用:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

