【发布时间】:2014-12-11 17:02:11
【问题描述】:
在 React.js 中,Angular 的 $watch 函数等价物是什么?
我想监听状态变化并调用 getSearchResults() 之类的函数。
componentDidMount: function() {
this.getSearchResults();
}
【问题讨论】:
标签: javascript reactjs
在 React.js 中,Angular 的 $watch 函数等价物是什么?
我想监听状态变化并调用 getSearchResults() 之类的函数。
componentDidMount: function() {
this.getSearchResults();
}
【问题讨论】:
标签: javascript reactjs
如果你使用 const [ name , setName ] = useState (' ') 之类的钩子,可以尝试以下方法:
useEffect(() => {
console.log('Listening: ', name);
}, [name]);
【讨论】:
在 2020 年,您可以像这样使用 useEffect 挂钩来监听状态变化
export function MyComponent(props) {
const [myState, setMystate] = useState('initialState')
useEffect(() => {
console.log(myState, '- Has changed')
},[myState]) // <-- here put the parameter to listen
}
【讨论】:
如上所述使用 useState 和 useEffect 是绝对正确的方法。但是如果 getSearchResults 函数返回订阅,那么 useEffect 应该返回一个负责取消订阅的函数。从 useEffect 返回的函数将在每次更改依赖项(上例中的名称)和组件销毁之前运行
【讨论】:
自 2019 年使用 useState 和 useEffect Hooks 的 React 16.8 以来,以下内容现在是等效的(在简单的情况下):
AngularJS:
$scope.name = 'misko'
$scope.$watch('name', getSearchResults)
<input ng-model="name" />
反应:
const [name, setName] = useState('misko')
useEffect(getSearchResults, [name])
<input value={name} onChange={e => setName(e.target.value)} />
【讨论】:
我没有使用过 Angular,但是阅读上面的链接,您似乎正在尝试编写一些您不需要处理的代码。您在 React 组件层次结构中更改状态(通过 this.setState()),React 将导致您的组件重新渲染(有效地“监听”更改)。 如果您想从层次结构中的另一个组件“监听”,那么您有两个选择:
【讨论】:
已经有一段时间了,但供将来参考:可以使用方法 shouldComponentUpdate()。
更新可能是由 props 或 state 的更改引起的。这些方法 在组件被调用时按以下顺序调用 重新渲染:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
【讨论】:
shouldComponentUpdate 返回一个布尔值,所以它可能不适合这个用例。
以下lifecycle methods会在状态改变时被调用。您可以使用提供的参数和当前状态来确定是否发生了有意义的变化。
componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)
【讨论】:
componentDidUpdate 是正确的处方。谢谢你。
componentWillUpdate 已被弃用:reactjs.org/blog/2018/03/27/update-on-async-rendering.html
componentDidUpdate 不会在收到新的 props 时触发,不一定只在状态改变时触发?
componentWillUpdate 已弃用。
我认为你应该在组件生命周期下面使用,就好像你有一个输入属性,更新时需要触发你的组件更新,那么这是最好的地方,因为它会在渲染之前被调用,你甚至可以更新组件要反映在视图上的状态。
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
【讨论】: