const ClientContextProvider = React.memo((props) => {
const [httpState, dispatchHttp] = useReducer(HttpReducer, initialHttpState())
const [username, setUsername] = useState(null)
const [givenName, setGivenName] = useState(null)
const [surname, setSurname] = useState(null)
useEffect(() => {
loadClient();
}, [])
const loadClient = () => {
console.log('Loading client info...')
const errorMsg = "Error, unable to get logged in client information!";
const callbacks = {
[Constants.SUCCESS]: { status: OK,
callback: (responseData) => {
setUsername(responseData.username)
setGivenName(responseData.givenName)
setSurname(responseData.surname)
loadAllJobs(username);
}}
};
axiosGetRequest(process.env.REACT_MYSERVICE_API_USER_LOGIN, errorMsg, dispatchHttp, callbacks);
}
const loadAllJobs = (username: string) => {
if (username === null) {
console.log('loadAllJobs: username is undefined')
} else {
const errorMsg = "Error, unable to get job information for logged in client!";
// Function carries on, calls api again using username as part of url
}
我试图在我的loadAllJobs()函数中访问用户名状态。我最初在useEffect中同时具有loadClient()和loadAllJobs()。在loadAllJobs函数中,用户名始终为null,因此我尝试在其上设置一个计时器,使其在7秒钟后运行,以为状态将有时间更新。这也不起作用。现在,我尝试将loadAllJobs函数粘贴到初始函数的回调中,以便在setStates也发生时发生。 这也不起作用,从我的loadAllJobs函数访问时,用户名仍然为null。 任何帮助表示赞赏!
答案 0 :(得分:1)
const callbacks = {
[Constants.SUCCESS]: {
status: OK,
callback: responseData => {
setUsername(responseData.username);
setGivenName(responseData.givenName);
setSurname(responseData.surname);
loadAllJobs(username);
},
},
};
这不能仅仅因为状态更新不同步而起作用。在组件生命周期中的此状态下,用户名仍然为null。它的值将在下一次渲染时更新,但那时为时已晚。
但是为什么要使其变得如此复杂?像这样呼叫loadAllJobs
,就可以了:loadAllJobs(responseData.username)
。