如何在react.js中监听状态变化?

JavaScript

小胖阳光

2020-03-11

React.js中与angular的$ watch函数等效的函数是什么?

我想听状态更改并调用类似getSearchResults()的函数。

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

第743篇《如何在react.js中监听状态变化?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
米亚Stafan 2020.03.11

我没有使用过Angular,但是阅读了上面的链接,似乎您正在尝试为不需要处理的内容编写代码。您对React组件层次结构中的状态进行更改(通过this.setState()),React将导致您的组件重新呈现(有效地“侦听”更改)。如果要从层次结构中的另一个组件“监听”,则有两个选择:

  1. 将处理程序从公共父级传递下来(通过props),并让它们更新父级的状态,从而导致父级以下的层次结构被重新呈现。
  2. 另外,为避免处理程序在层次结构中层叠泛滥,您应该查看流通模式,该模式将状态移入数据存储区并允许组件监视其变化。Fluxxor插件是管理这个非常有用的。
村村伽罗Mandy 2020.03.11

状态更改时,将调用以下生命周期方法您可以使用提供的参数和当前状态来确定是否有意义的更改。

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
小小仲羽 2020.03.11

已经有一段时间了,但供以后参考:可以使用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()

ref: https://reactjs.org/docs/react-component.html

蛋蛋蛋蛋 2020.03.11

我认为您应该在“组件生命周期”下使用,就像您有一个输入属性,该属性在更新时需要触发您的组件更新一样,因此这是最好的选择,因为它将在渲染之前被调用,甚至可以将组件状态更新为反映在视图上。

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android