2017-10-11 2 views

답변

2

을 시도

을 업데이트되지 않은 변수 component_template 상태를 볼 수 있습니다

componentDidMount() { 
    var parent_object=this; 
      axios.get('/template.php') 
        .then((result)=> { 
         console.log(result.data); 

    parent_object.setState({component_template:result.data})//not updating 

        }); 

    console.log("here"); 
    console.log(this.state.component_template); 
} 

아래 시도 :

setState()가 항상 구성 요소를 즉시 업데이트하지는 않습니다. 나중에 업데이트가있을 때까지 업데이트를 일괄 처리하거나 지연시킬 수 있습니다. 이것은 setState()를 잠재적 인 함정이라고 부른 직후 this.state를 읽도록합니다. 대신 componentDidUpdate 또는 setState 콜백 (setState (updater, callback))을 사용하십시오.이 중 하나는 업데이트가 적용된 후에 실행됩니다.

따라서 상태가 제대로 업데이트되고 있지만 console.log가 업데이트 된 값을 읽지 못할 수 있습니다. 콜백을 사용하거나 componentDidUpdate 내부를 확인하십시오.

3

React setState is asynchronous! 상태 값이 업데이트 된 후에는 콜백 함수를 호출 할 수있는

componentDidMount() { 
     axios.get('/template.php') 
       .then((result)=> { 
       console.log(result.data); 
       this.setState({component_template:result.data},()=>{ 
        console.log(this.state.component_template); 
       }) 

     }); 

}

0

setState를 반응 비동기 호출입니다. setSate 이후의 콘솔은 업데이트 된 값을 보장하지 않습니다.

콘솔을 setState를 사용하여 콜백으로 추가하거나 render 메서드 내에서 첫 번째 행으로 업데이트 된 상태 값을 확인합니다.

관련 문제