我遇到了应该不会发生的问题:
请参见根据三元运算的结果设置initialUserState
。但是,此操作应该在此处返回false(因为user
对象中没有context
属性。(您可以在下面的调试器中看到它)
这里可能发生什么事?
数据来自NextJS应用程序中的上一个请求(我正在使用Firefox和Firefox Private模式)。仅当请求彼此相邻时,才会发生这种情况。因此,我认为这是一个并发问题,但无法理解为什么javascript在这种情况下会失败。如果我在这里再次声明,initialUserState
将如何保持该值。
import {userInitialState} from "./UserContext";
import {listInitialState} from "./ListContext";
import {createContext, useState} from "react";
/**
* Sets the initial application context
*/
export default class ApplicationContext {
userContext;
listContext;
/**
* Will set the initial application state.
* @param context
*/
constructor(context) {
let initialUserState = context.hasOwnProperty('user') ? context.user : userInitialState;
const userContextUpdater = () => {
let [state, setState] = useState({...initialUserState})
return [state, setState];
}
this.userContext = createContext(userContextUpdater);
let initialListState = context.hasOwnProperty('list') ? context.list : listInitialState;
const listContextUpdater = () => {
let [state, setState] = useState({...initialListState})
return [state, setState];
}
this.listContext = createContext(listContextUpdater);
}
/**
* Returns the UserContext
* @returns {*}
*/
getUserContext = () => {
return this.userContext;
}
/**
* Returns the List context
* @returns {*}
*/
getListContext = () => {
return this.listContext;
}
}
_app.js
import ApplicationContext from "../lib/Context/ApplicationContext";
import {useContext} from "react";
export default function RankerApp({Component, pageProps}) {
const applicationContext = new ApplicationContext(pageProps);
const ListContext = applicationContext.getListContext();
const UserContext = applicationContext.getUserContext();
const [listState, setListState] = useContext(ListContext)();
const [userState, setUserState] = useContext(UserContext)();
return (
<ListContext.Provider value={[listState, setListState]}>
<UserContext.Provider value={[userState, setUserState]}>
<Component {...pageProps} applicationContext={applicationContext}/>
</UserContext.Provider>
</ListContext.Provider>
);
}
UserContext.js
export const userInitialState = {
currentUserId: undefined,
users: {},
}
这让我发疯,看起来这是某种并发性问题,否则我无法解释,因为如果请求间隔时间就不会发生