如何监听 react.js 中的状态变化? [英] How to listen state changes in react.js?

查看:36
本文介绍了如何监听 react.js 中的状态变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React.js 中,Angular 的 $watch 函数是什么?

What is the angular's $watch function equivalent in React.js?

我想监听状态变化并调用 getSearchResults() 之类的函数.

I want to listen state changes and call a function like getSearchResults().

componentDidMount: function() {
    this.getSearchResults();
}

推荐答案

我没有使用过 Angular,但是阅读上面的链接,似乎您正在尝试为不需要处理的东西编码.您对 React 组件层次结构中的状态进行更改(通过 this.setState()),React 将导致您的组件重新渲染(有效地监听"更改).如果您想从层次结构中的另一个组件收听",那么您有两个选择:

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:

  1. 从公共父级向下传递处理程序(通过 props)并让它们更新父级的状态,从而导致父级下方的层次结构被重新渲染.
  2. 或者,为了避免处理程序级联到层次结构的爆炸式增长,您应该查看 flux 模式,它将您的状态移动到数据存储中,并允许组件观察它们的变化.Fluxxor 插件对于管理此问题非常有用.
  1. 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.
  2. 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 plugin is very useful for managing this.

这篇关于如何监听 react.js 中的状态变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆