React setState 콜백을 사용하는 경우
반응 구성 요소 상태가 변경되면 render 메소드가 호출됩니다. 따라서 상태가 변경되면 렌더링 메소드 본문에서 작업을 수행 할 수 있습니다. 그러면 setState 콜백에 대한 특별한 사용 사례가 있습니까?
예부터이 setState
의 작동 asynchronous
방법. 즉 setState
, this.state
변수 호출 후 즉시 변경되지 않습니다. 따라서 상태 변수에 상태를 설정 한 직후 작업을 수행하고 결과를 반환하려는 경우 콜백이 유용합니다.
아래 예를 고려하십시오
....
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 함수 자체에서 코드를보다 체계적이고 이해하기 쉽게 처리 할 수 있다면 더 좋고 깔끔한 방법입니다.
이 경우 콜백이 유용합니다
....
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" });
}
},
....
또 다른 예로는 dispatch
상태가 변경되었을 때 원하는 조치와 조치가 있습니다. 리 render()
렌더링이 발생할 때마다 호출되므로 콜백이 아닌 콜백에서 수행하기를 원하므로 콜백 이 필요한 많은 시나리오가 가능합니다.
다른 경우는 API Call
특정 상태 변경을 기반으로 API 호출을 수행해야 할 경우가 발생할 수 있습니다. 렌더 메소드에서 렌더링을 수행 할 때마다 렌더링이 onState
변경 될 때마다 또는 일부 Prop이 Child Component
변경으로 전달 되었기 때문에 호출됩니다 .
이 경우 a setState callback
를 사용 하여 업데이트 된 상태 값을 API 호출에 전달 하려고합니다.
....
changeTitle: function (event) {
this.setState({ title: event.target.value }, () => this.APICallFunction());
},
APICallFunction: function () {
// Call API with the updated value
}
....
내 마음에 오는 유스 케이스는 api
호출이며 each
상태 변경을 위해 실행되므로 렌더링에 들어가면 안됩니다 . 그리고 API 호출은 모든 렌더링이 아닌 특수 상태 변경에서만 수행되어야합니다 .
changeSearchParams = (params) => {
this.setState({ params }, this.performSearch)
}
performSearch = () => {
API.search(this.state.params, (result) => {
this.setState({ result })
});
}
따라서 상태가 변경되면 렌더링 메소드 본문에서 작업을 수행 할 수 있습니다.
Very bad practice, because the render
-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount
for example.
this.setState({
name:'value'
},() => {
console.log(this.state.name);
});
Consider setState call
this.setState({ counter: this.state.counter + 1 })
IDEA 1
setState may be called in async function
So you cannot rely on this
. If the above call was made inside a async function this
will refer to state of component at that point of time but we expected this to refer to property inside state at time setState calling or beginning of async task. And as task was async call thus that property may have changed in time being. Thus it is unreliable to use this
keyword to refer to some property of state thus we use callback function whose arguments are previousState and props which means when async task was done and it was time to update state using setState call prevState will refer to state now when setState has not started yet. Ensuring reliability that nextState would not be corrupted.
Wrong Code: would lead to corruption of data
this.setState(
{counter:this.state.counter+1}
);
Correct Code with setState having call back function:
this.setState(
(prevState,props)=>{
return {counter:prevState.counter+1};
}
);
Thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setState as callback function.
IDEA 2
The setState call may be async
itself bcz React may try to combine two or more setState calls together for performance improvement. Anyways that's unreliable. Suppose two setState calls are fired at t=0. They both were referring to same state (state_0) before call, being async we cannot rely which one will end first. Suppose one call may lead to state_1 as one of them end. And other call where state was referring initial state (state_0) may lead to state_3. And this may lead to corruption of states and its data. Using a callback where arguments to callback function is prevState, props. It makes sure that if one of them ends first leading to state_1, the next setState will always refer prevState as initial state. Thus always ensure that data don't get corrupted. It is very unlikely for data corruption this way due to setState being called simultaneously. But if we are required our next state to be dependent on prevState then use callback always.
I have tried to explain it in codepen here CODE PEN
참고URL : https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback
'Programming' 카테고리의 다른 글
안드로이드 충돌 로그를 얻는 방법? (0) | 2020.06.15 |
---|---|
무엇을 할 수 있습니까 (0) | 2020.06.15 |
기존 테이블에 자동 증분 기본 키 삽입 (0) | 2020.06.15 |
Virtualenv에 다른 버전의 Python을 설치할 수 있습니까? (0) | 2020.06.15 |
Java에서 개인 정적 변수를 사용하는 것은 무엇입니까? (0) | 2020.06.15 |