2017-01-17 3 views
0

this.setState이 상태를 즉시 변경하는지 궁금합니다. 그렇게하지 않는 것 같습니다. OK입니다 -ReactJS : this.setState가 즉시 적용됩니까?

, 설명의이 체크 박스가 있다고 가정하자하려면 ....이 예에서

class Example extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
    switch: false 
    }; 
    this.switch = this.switch.bind(this); 
} 

clickCoverSwitch(){ 
    console.log("Before clicking - ", this.state.switch); 
    this.setState({switch: !this.state.switch}); 
    console.log("Now, the state is - ", this.state.switch); 
} 

render() { 
    return (
     <input onClick={this.clickCoverSwitch} defaultChecked={this.state.coverSwitch} type="checkbox"> 
     </input> 
    ); 
} 

이 체크 박스는 기본적으로 꺼져 있습니다.

그러나 스위치 (즉, 체크 박스)를 클릭하면 콘솔에 다음 메시지가 표시됩니다.

Now, the state is - false

두 번째 줄

Before clicking - false

this.state.switchthis.setState({switch: !this.state.switch})를 통해 변경해야하기 때문에, true 보여줄 예정이다.

나는 이것을 어떻게 해석해야하는지 잘 모르겠습니다. 조언을 주시면 감사하겠습니다.

+0

아니요, 비동기입니다. 설정 한 후에 상태를 기록하려면'setState'의 콜백을 사용할 수 있습니다 : http://stackoverflow.com/questions/40641998/when-is-it-safe-to-save-state-in-react/ 40642027 # 40642027 –

+0

부분적으로 참입니다. 'setState'는 동기식 일 수도 있습니다. – Andreyco

답변

7

setState()는 this.state를 즉시 변경하지 않고 보류중인 상태 전환을 만듭니다. 이 메소드를 호출 한 후 this.state에 액세스하면 잠재적으로 기존 값을 리턴 할 수 있습니다.

this.setState((prevState) => ({ switch: !prevState.switch})); 

상태 변경을 보류 중의 복수의가있는 경우이 방법, 그들은 늘 서로를 덮어 :

//This way leads to undesirable results 
Somefunction() { 
    this.setState({ counter: this.state.counter + 3}) 
    this.setState({ counter: this.state.counter + 5}) 
} 
//this.state.counter === 5 here 

betterfunction() { 
    this.setState((prevState) => ({ counter: prevState.counter + 3})) 
    this.setState((prevState) => ({ counter: prevState.counter + 5})) 
} 
//The second setState will change based on the first one's values instead of overwritting them 
//this.state.counter === 8 here 

이전 상태를 기준으로 상태를 변경하는 구문을 사용하기 위해 더 나은 가치를

자세한 정보는 여기를 참조하십시오 : https://facebook.github.io/react/docs/react-component.html#setstate

4

글쎄, 그것은 달라집니다 ... 반응의 setState은 sync와 async 일 수도 있습니다. 문맥 문제를 유발하는 문제 - 자세한 내용은 topic here

일반 규칙 - setState은 동기식이 아닙니다. 상태가 전파 될 때 작업을 수행해야하는 경우 setState 완료 콜백을 사용하십시오 (두 번째 매개 변수는 setState으로 전달됨).

+0

다음과 같이 콜백을 쓸 수 있습니다. this.setState ({switch :! this.state.switch}, console.log ("이제 상태는 -", this.state.switch)); – AmitJS94

+1

정말 이니? Andreco는 "console.log ("상태는 - ", this.state.switch)의 콜백 값을'setState'의 콜백 값으로 호출합니다. – Andreyco

+1

가장 안전한 방법은 콜백을 사용하는 것입니다. 그러나 여러 후속 상태 변경을 원할 경우 동기화시기와 비동기시기를 조사 할 수 있습니다 – Jayce444

관련 문제