所以我正在运行一个具有以下设置的应用程序:
然而,在我当前的设置中,当钩子状态确实在数组中获得一个新项目时,组件 A 不会重新渲染,任何想法为什么会发生这种情况?我提供了一些清除代码:
const initialValue = [];
function getLocalStorageItem() {
const item = window.localStorage.getItem("queries");
return item ? JSON.parse(item) : initialValue;
}
function useLocalStorageQueryHistory() {
const { dispatch } = useAlertContext();
const [recentQueries, setRecentQueries] = useState(() => {
try {
return getLocalStorageItem();
} catch (error) {
dispatch(receiveMessageInterceptor(error));
return initialValue;
}
});
const setValue = (value) => {
try {
const recentQueries = getLocalStorageItem();
if (recentQueries.length >= 6) {
recentQueries.shift();
}
if (!recentQueries.some((query) => query.params === value.params)) {
window.localStorage.setItem(
"queries",
JSON.stringify([...recentQueries, value])
);
setRecentQueries([...recentQueries, value]);
}
} catch (error) {
dispatch(receiveMessageInterceptor(error));
}
};
return { recentQueries, setValue };
}
function RecentQueriesContainer() {
const { recentQueries } = useLocalStorageQueryHistory();
return (
<Container disableGutters>
{recentQueries.length ? (
recentQueries.map((item) => (
<Card key={`${item.params}`}>
<CardHeader
title={item.description}
/>
<Typography variant={"body2"}>
Mode: {item.params.split("&visualization=")[1]}
</Typography>
<Typography variant={"body2"}>Unit: {item.unit}</Typography>
</Card>
))
) : (
<Typography
variant={"subtitle2"}
color={"secondary"}
align={"center"}
mt={2}
>
No recent queries available
</Typography>
)}
</Container>
);
}
简单地使用useEffect中的setter
useEffect(() => {
const {
features,
description,
unit,
amountOfCountries,
} = geoJsonFromSelectedStatistic;
if (features) {
setValue({
description,
unit,
amountOfCountries,
params: window.location.search,
});
}
}, [geoJsonFromSelectedStatistic]);
答案 0 :(得分:1)
我相信这是因为您没有创建上下文。钩子默认不共享状态,它们只共享状态逻辑。
所以组件 A 和 B 使用相同的钩子,但它们之间的状态不同。
尝试创建上下文,然后使用它来共享状态。它应该可以正常工作:)
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState();
return (
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
{children}
</AuthContext.Provider>
);
};
export function useAuth(){
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
像这样,其中 AuthProvider 就像您的自定义钩子,其值是您的钩子导出的值。这些将可用于将上下文与 useAuth
不要忘记用 <AuthProvider />
答案 1 :(得分:0)
我遵循@thales-kenne 的方法并使用了我已经设置了 UI 上下文的 react 上下文并将其扩展如下:
const initialState = {
sidebarOpen: false,
...
recentQueries: getLocalStorageItem(),
};
function uiReducer(state = initialState, action) {
switch (action.type) {
case SIDEBAR: {
return {
...state,
sidebarOpen: action.sidebarOpen,
};
}
...
case RECENT_QUERIES: {
return {
...state,
recentQueries: action.recentQueries,
};
}
default:
return state;
}
}
export function getLocalStorageItem() {
const initialValue = [];
try {
const item = window.localStorage.getItem("queries");
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
}
export const setRecentQueries = (value) => {
try {
const recentQueries = getLocalStorageItem();
if (recentQueries.length >= 5) {
recentQueries.shift();
}
if (!recentQueries.some((query) => query.uri === value.uri)) {
window.localStorage.setItem(
"queries",
JSON.stringify([...recentQueries, value])
);
return {
type: RECENT_QUERIES,
recentQueries: [...recentQueries, value],
};
}
} catch (error) {
console.error(error);
}
};