2017-11-17 3 views
2

componentDidMount()에 대한 일부 정보를 검색하기 위해 API get 요청을 요구하는 구성 요소가 있습니다. 요청을 얻으려면 상태에 저장된 정보를 사용하여 ComponentWillMount()에있는 함수를 통해 설정합니다.WillMount()에 설정된 상태가 DidMount()에서 액세스 할 수 없음

내 이 실행되면 내 render() 메서드가 작동하지만 상태가 설정되지 않았으므로 didMount()에 도달하지만 데이터가 아직 상태가 아니기 때문에 실패합니다. 내가 어디로 잘못 가고 있니?

편집 : 모든 기능 (도시하지 않음) 생성자 그 만드는 경우

componentWillMount() { 
    this.enforceEmployeeAuth(); 
    this.loadEmployeeInfo(); 
    } 

    componentDidMount() { 
    this.fetchSurveyFields(); 
    } 

    // Initial check to confirm if the user should be allowed to access any information. 
    enforceEmployeeAuth() { 
    // Get request to confirm that the current user is of type EMPLOYEE 
    API.get("user/employee_auth", {}, (res) => { 
     // Employee Auth: True if employee, else false 
     this.setState({ 
     employee_auth: res.employee_auth, 
     }); 
    }); 
    } 

    // Load up relevant information for currentUser/employee 
    loadEmployeeInfo() { 
    API.get("client/currentEmployee", {}, function(res) { 
     this.setState({ 
     employee    : res.employee, 
     employee_company  : res.employee_company, 
     }) 
    }.bind(this)); 
    } 

    fetchSurveyFields() { 
    debugger 
    API.get('client/survey', { 
     survey: this.state.employee_company.survey_name 
    }, function(res) { 
     debugger 
    }) 
    } 

    render() { 

    debugger 

    return (
     <h2 className="text-charcoal text-left">Employee Rubric</h2> 
    ) 
    } 
+0

처럼 당신은) (당신이 유 상태가 제대로 loadEmployeeInfo 내부 데이터로 설정되어 있는지 확인 했나 데이터 – Cruiser

+0

를 사용하기 전에 돌아오고 갔지의 결과를 기다리는 방법이 필요 해요 from componentWillMount() method –

+0

디버거를 사용하여 플로우를 점검했습니다. 'willMount()'-> 함수를 실행 중 .... 'render()'-> 상태 업데이트 없음 ... 'didMount()'-> 상태가 아직 변경되지 않았습니다. 함수가 실패 할 것입니다 .... 'render()'-> 첫 번째 상태 변경이 렌더링됩니다 .... 'render()'-> 두 번째 상태 변경이 렌더링됩니다 –

답변

1

귀하의 기능, 그들은 반환 한 후에 그들이 요청 '결과 상태를 설정 의미 비동기 요청에 의존에 바인딩 감각.

메서드를 렌더링 할 때 상태의 유효성을 검사하고 유효하지 않으면 null을 반환합니다. 렌더링 메소드는 다음에 상태가 설정 될 때 다시 호출됩니다 (즉, 콜백에 상태가 설정되어 요청이 성공한 경우).

0

상위 구성 요소에서 소품으로 인증 토큰을 전달한 다음 componentWillReceiveProps 후크를 사용하여 API에 대한 요청을 시작하는 방법은 어떻습니까?

2

두 api 호출에서 반환 한 약속을 저장해야합니다. 그리고 componentDidMount에있는 그것들을 해결할 때, 당신은 fetchSurveyFields에 대한 API 호출을해야합니다. 전화했을 때이

componentWillMount() { 
    this.promises = []; 

    this.promises.push(this.enforceEmployeeAuth()); 
    this.promises.push(this.loadEmployeeInfo()); 
    } 

    componentDidMount() { 
    Promise.all(this.promises) 
     .then(([resp1, resp2]) => { 
     //You can see here if you still wanna set state. 
     this.fetchSurveyFields(); 
     }); 

    } 

    // Initial check to confirm if the user should be allowed to access any information. 
    enforceEmployeeAuth() { 
    // Get request to confirm that the current user is of type EMPLOYEE 
    API.get("user/employee_auth", {}, (res) => { 
     // Employee Auth: True if employee, else false 
     this.setState({ 
     employee_auth: res.employee_auth, 
     }); 
    }); 
    } 

    // Load up relevant information for currentUser/employee 
    loadEmployeeInfo() { 
    API.get("client/currentEmployee", {}, function(res) { 
     this.setState({ 
     employee    : res.employee, 
     employee_company  : res.employee_company, 
     }) 
    }.bind(this)); 
    } 

    fetchSurveyFields() { 
    debugger 
    API.get('client/survey', { 
     survey: this.state.employee_company.survey_name 
    }, function(res) { 
     debugger 
    }) 
    } 

    render() { 

    debugger 

    return (
     <h2 className="text-charcoal text-left">Employee Rubric</h2> 
    ) 
    } 
관련 문제