- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
为什么使用 componentDidUpdate
更多推荐超过setState
React 组件中的回调函数(可选的第二个参数)(如果需要同步 setState 行为)?
由于setState
是异步的,我正在考虑使用 setState
回调函数(第二个参数)确保代码在状态更新后执行,类似于 then()
为了 promise 。特别是如果我需要在后续 setState
之间重新渲染来电。
然而,官方的 React Docs 说“setState() 的第二个参数是一个可选的回调函数,一旦 setState 完成并重新渲染组件就会执行。一般我们建议使用 componentDidUpdate() 来代替这种逻辑。”
这就是他们在那里所说的一切,所以看起来有点模糊。我想知道是否有更具体的原因建议不要使用它?如果可以的话,我会问 React 的人自己。
如果我希望按顺序执行多个 setState 调用,则 setState 回调在代码组织方面似乎比 componentDidUpdate 更好 - 回调代码是在 setState 调用中定义的。如果我使用 componentDidUpdate 我必须检查相关的状态变量是否发生了变化,并在那里定义后续代码,这不太容易跟踪。此外,在包含 setState 调用的函数中定义的变量将超出范围,除非我也将它们放入状态。
以下示例可能会显示何时使用 componentDidUpdate 可能会很棘手:
private functionInComponent = () => {
let someVariableBeforeSetStateCall;
... // operations done on someVariableBeforeSetStateCall, etc.
this.setState(
{ firstVariable: firstValue, }, //firstVariable may or may not have been changed
() => {
let secondVariable = this.props.functionFromParentComponent();
secondVariable += someVariableBeforeSetStateCall;
this.setState({ secondVariable: secondValue });
}
);
}
public componentDidUpdate(prevProps. prevState) {
if (prevState.firstVariableWasSet !== this.state.firstVariableWasSet) {
let secondVariable = this.props.functionFromParentComponent();
secondVariable += this.state.someVariableBeforeSetStateCall;
this.setState({
secondVariable: secondValue,
firstVariableWasSet: false,
});
}
}
private functionInComponent = () => {
let someVariableBeforeSetStateCall = this.state.someVariableBeforeSetStateCall;
... // operations done on someVariableBeforeSetStateCall, etc.
this.setState({
firstVariable: firstValue,
someVariableBeforeSetStateCall: someVariableBeforeSetStateCall,
firstVariableWasSet: true });
//firstVariable may or may not have been changed via input,
//now someVariableBeforeSetStateCall may or may not get updated at the same time
//as firstVariableWasSet or firstVariable due to async nature of setState
}
最佳答案
Why is using
componentDidUpdate
more recommended over thesetState
callback function?
setState()
的回调参数时,您可能有两次单独调用
setState()
在更新相同状态的不同地方,您必须记住在两个地方使用相同的回调。
private method1(value) {
this.setState({ value }, () => {
SomeAPI.gotNewValue(this.state.value);
});
}
private method2(newval) {
this.setState({ value }); // forgot callback?
}
componentDidUpdate()
被推荐:
public componentDidUpdate(prevProps, prevState) {
if (this.state.value !== prevState.value) {
SomeAPI.gotNewValue(this.state.value);
}
}
private method1(value) {
this.setState({ value });
}
private method2(newval) {
this.setState({ value });
}
setState()
的回调参数在组件重新渲染后执行。但是,多次调用
setState()
由于批处理,不保证会导致多次渲染。
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
}
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate: ' + this.state.value);
}
onClick = () => {
this.setState(
{ value: 7 },
() => console.log('onClick: ' + this.state.value));
this.setState(
{ value: 42 },
() => console.log('onClick: ' + this.state.value));
}
render() {
return <button onClick={this.onClick}>{this.state.value}</button>;
}
}
setState()
调用
onClick()
处理程序,每个都只是将新的状态值打印到控制台。
onClick()
打印值
7
然后
42
.但实际上,它会打印
42
两次!这是因为两个
setState()
调用被批处理在一起,并且只会导致一次渲染发生。
componentDidUpdate()
它还打印新值。由于我们只发生了一次渲染,它只执行一次,并打印值
42
.
componentDidMount()
通常要容易得多。 .
onclick
)中,有时甚至是生命周期方法。所有其他上下文从不使用批处理。
setState
比较好打回来?
setState
回调而不是
componentDidUpdate
, 并将其包装在一个 promise 中。
Child
看起来像这样的组件:
interface IProps {
onClick: () => Promise<void>;
}
class Child extends React.Component<IProps> {
private async click() {
await this.props.onClick();
console.log('Parent notified of click');
}
render() {
return <button onClick={this.click}>click me</button>;
}
}
Parent
单击子项时必须更新某些状态的组件:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { clicked: false };
}
private setClicked = (): Promise<void> => {
return new Promise((resolve) => this.setState({ clicked: true }, resolve));
}
render() {
return <Child onClick={this.setClicked} />;
}
}
setClicked
,我们必须创建一个
Promise
返回子节点,唯一的方法是将回调传递给
setState
.
Promise
在
componentDidUpdate
,但即使是这样,由于批处理,它也无法正常工作。
Since
setState
is asynchronous, I was thinking about using thesetState
callback function (2nd argument) to ensure that code is executed after state has been updated, similar to.then()
for promises.
setState()
的回调与 Promise 的工作方式不同,因此最好将您的知识分开。
Especially if I need a re-render in between subsequent
setState
calls.
setState()
之间重新渲染组件?电话?
this.props.functionFromParentComponent()
,它返回一个值,然后您可以使用该值来计算某些状态。
getDerivedStateFromProps()
中的状态值.
//firstVariable may or may not have been changed,
//now someVariableBeforeSetStateCall may or may not get updated at the same time
//as firstVariableWasSet or firstVariable due to async nature of setState
setState()
的异步特性并不意味着状态没有得到正确更新。代码应该按预期工作。
关于javascript - 与 setState 回调相比,使用 componentDidUpdate 有什么优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501409/
我可以在传递给 this.setState() 的回调定义中显式调用 this.setState() 吗? this.setState( { openA:true }, () => {
我有一个从 api 获取数据的场景。在这种情况下,每当我从商店获取新值时,我的 componentWillReceiveProps() 就会被触发。 componentWillReceiveProps
在这个 componentDidUpdate 方法中,在执行 setState 将引号设置为从 fetch 返回的内容后,我必须使用回调再次执行 setState 以将 randomQuoteInde
正如 another question 中向我指出的那样,如果我在 setState、randomQuoteIndex() 中有一个不带参数的函数调用,并且该函数使用该 setState 中设置的状态
问题:当我使用 this.setState 并在回调中输出状态时,它根本不会改变,但是当我将 setstate 嵌套在 setstate 中时,它就会正常工作。 例子:这行不通- this.setSt
这个问题在这里已经有了答案: Why does setState take a closure? (2 个答案) 关闭 4 年前。 我对这两者的区别还是有点迷惑 isBusy = false;
当我使用 setState () 文本出现在调试控制台中.. setState() callback argument returned a Future. The setState() method
这个问题已经有答案了: Are 'Arrow Functions' and 'Functions' equivalent / interchangeable? (4 个回答) React - unca
之间的区别 - this.setState({value: 'xyz', name: 'john', color: 'orange'}) 对比 setValue('xyz'); setName('jo
之间的区别 - this.setState({value: 'xyz', name: 'john', color: 'orange'}) 对比 setValue('xyz'); setName('jo
我在运行代码时收到以下警告: Line 48: Do not mutate state directly. Use setState() react/no-direct-mutation-state
我是 React 的新手,我注意到我们使用 this.setState() 而不是 super.setState() 请我清楚地解释为什么我们用它来调用父类(super class)方法??示例: c
我一生都无法在我的 react 组件中传递这个 TypeError 。我已阅读所有相关主题并实现了几乎所有建议的修复,但均无济于事。 import React, { Component } from
我知道这可能是一个 JavaScript 问题而不是 React 问题,但我无法理解 React setState 的上述签名。 函数参数列表中的方括号和逗号有什么作用? 我知道如何将它与更新程序一起
是否可以在this.setState的回调中调用this.setState? 我正在制作一个 Roguelike Dungeon 并有一个设置,其中在 this.setState 的回调中使用了一个辅
我正在使用 react-navigation 进行路由。在一个组件上,我尝试设置 navigationOptions 以显示汉堡包按钮以打开和关闭侧边栏(抽屉)。所以 onPress 我试图为我的侧边
在之前的 React 版本中,我们可以在状态更改后执行代码,方法如下: setState( prevState => {myval: !prevState.myval}, () => { co
有一个 react 问卷组件,它将选定的答案添加到 this.state = {answer: []} 中,效果很好。同时,当用户更新答案时,它会添加为另一个对象。当questionID相同时,是否有
我正在使用 WebSocket 与我的服务器进行通信,并在我的 handleSubmit() 函数上输入一些值,并在此基础上与服务器进行通信并将我的状态更新为数据从 ws 收到。所以,第一次,一切都工
componentDidMount(prevProps, prevState, prevContext) { let [audioNode, songLen] = [this.refs.aud
我是一名优秀的程序员,十分优秀!