gpt4 book ai didi

javascript - WillMount() 中设置的状态无法在 DidMount() 中访问

转载 作者:行者123 更新时间:2023-11-29 19:00:13 25 4
gpt4 key购买 nike

我有一个组件需要 API get 请求来检索有关 componentDidMount() 的一些信息。该获取请求依赖于存储在状态中的信息,该状态是我通过在 ComponentWillMount() 上调用的函数设置的。

我的 willMount() 运行,然后我点击了我的 render() 方法,但是状态还没有设置,然后它点击了 didMount( ) 但由于数据尚未处于状态而失败。我哪里错了?

编辑:所有函数都绑定(bind)在构造函数中(未显示)

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>
)
}

最佳答案

您应该保存两个 api 调用返回的 promise 。然后在解决 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>
)
}

关于javascript - WillMount() 中设置的状态无法在 DidMount() 中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com