我正在使用 React 和 Typescript。
即使我正在更新 .log 文件中的值,当我 consoloe.log 时,它initialData
仍然保持不变。null
useEffet
为什么这段代码会在循环中不断发出请求?
这是我的context
:
import React, {
Dispatch,
SetStateAction,
createContext,
useContext,
useState,
} from 'react';
interface InitialDataType {
GameName: string;
GameUrl: string;
HasRegulation: boolean;
HideNavBar: boolean;
HideSessionNetLoss: boolean;
HideSessionTimer: boolean;
RegulationAction: string;
RegulationModel?: string;
TournamentId?: number;
TournamentType?: number;
TournamentsBaseUrl?: string;
Url: string;
VendorController: string;
}
interface InitialDataContextInterface {
initialData: InitialDataType | null;
setInitialData: Dispatch<SetStateAction<InitialDataType | null>>;
}
const Context = createContext({} as InitialDataContextInterface);
const InitialDataProvider = ({ children }) => {
const [initialData, setInitialData] = useState<InitialDataType | null>(
null
);
return (
// eslint-disable-next-line react/jsx-no-constructed-context-values
<Context.Provider value={{ initialData, setInitialData }}>
{children}
</Context.Provider>
);
};
export default InitialDataProvider;
export const useInitialData = () => useContext(Context);
这是我的主页组件:
import React, { useContext, useEffect } from 'react';
import axios from 'axios';
import UkRegulation from '../../regulations/UkRegulation/UkRegulation';
import GameIframe from '../../components/GameIframe/GameIframe';
import { useInitialData } from '../../context/InitialDataContext';
const Home = () => {
const { initialData, setInitialData } = useInitialData();
useEffect(() => {
axios
.get(
'https://myUrl.com/my-endpoint'
)
.then((response) => {
setInitialData(response.data);
console.log('InitialData', initialData);
})
.catch((error) => {
console.log(error);
});
}, []);
return (
<div>
<UkRegulation />
<GameIframe />
</div>
);
};
export default Home;