何时使用React setState回调 [英] When to use React setState callback
问题描述
当反应组件状态改变时,将调用render方法。因此,对于任何状态更改,都可以在渲染方法主体中执行操作。那么,setState回调是否有特定的用例?
When a react component state changes, the render method is called. Hence for any state change, an action can be performed in the render methods body. Is there a particular use case for the setState callback then?
推荐答案
是的,因为 setState
以异步
的方式工作。这意味着在调用 setState
之后, this.state
变量不会立即更改。因此,如果要在状态变量上设置状态后立即执行操作,然后返回结果,则回调将非常有用
Yes there is, since setState
works in an asynchronous
way. That means after calling setState
the this.state
variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful
请考虑以下示例
....
changeTitle: function changeTitle (event) {
this.setState({ title: event.target.value });
this.validateTitle();
},
validateTitle: function validateTitle () {
if (this.state.title.length === 0) {
this.setState({ titleError: "Title can't be blank" });
}
},
....
以上代码可能无法按预期方式工作,因为 title
变量可能没有在对其执行验证之前发生突变。现在您可能想知道我们可以在 render()
函数本身中执行验证,但是如果可以在changeTitle函数本身中进行处理,那将是更好和更简洁的方法,因为
The above code may not work as expected since the title
variable may not have mutated before validation is performed on it. Now you may wonder that we can perform the validation in the render()
function itself but it would be better and a cleaner way if we can handle this in the changeTitle function itself since that would make your code more organised and understandable
在这种情况下,回叫很有用
In this case callback is useful
....
changeTitle: function changeTitle (event) {
this.setState({ title: event.target.value }, function() {
this.validateTitle();
});
},
validateTitle: function validateTitle () {
if (this.state.title.length === 0) {
this.setState({ titleError: "Title can't be blank" });
}
},
....
另一个例子当您要调度
并在状态更改时采取操作。您将希望在回调中执行此操作,而不是 render()
,因为每次进行重新渲染时都会调用它,因此可能需要回调的情况很多。
Another example will be when you want to dispatch
and action when the state changed. you will want to do it in a callback and not the render()
as it will be called everytime rerendering occurs and hence many such scenarios are possible where you will need callback.
另一种情况是 API调用
Another case is a API Call
当您需要基于特定的状态更改进行API调用时,可能会出现这种情况,如果在render方法中进行此调用,则会在每个渲染 onState $时调用它c $ c>更改或由于传递到
子组件
的某些属性更改。
A case may arise when you need to make an API call based on a particular state change, if you do that in the render method, it will be called on every render onState
change or because some Prop passed down to the Child Component
changed.
在这种情况下,您将想要使用 setState回调
将更新后的状态值传递给API调用
In this case you would want to use a setState callback
to pass the updated state value to the API call
....
changeTitle: function (event) {
this.setState({ title: event.target.value }, () => this.APICallFunction());
},
APICallFunction: function () {
// Call API with the updated value
}
....
这篇关于何时使用React setState回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!