我有一个反应应用程序,有多个标签。当用户转到" data“选项卡时,它将从API调用中获取数据,并将数据设置为一种反应状态。但是,如果用户从" data“选项卡转到"Home”选项卡,然后返回到" data“选项卡,则必须再次从API调用中获取数据,因为状态中的数据已经消失。
所需功能的Psuedocode:
const OutputTab: React.FC<PageProps> = ({ match, pageName }) => {
const [outputData, setOutputData] = useState<outputsInterface[]>([]);
useIonViewWillEnter(() => {
if (!outputData) {
fetchOutputs();
}
});
const fetchOutputs = () => {
let response = fetch("....");
setOutputData(response.json);
};
};存储状态数据的最简单方法是什么?所需的功能是当用户返回到选项卡时,我们可以简单地检查数据是否已经存在,而不是进行另一个API调用来重新获取数据。
我想到了使用localStorage或sessionStorage的可能解决方案,但我更喜欢将数据存储在内存中而不是存储中。我需要像Redux这样的东西来完成这个任务吗?
发布于 2020-06-06 19:30:37
完整的解决方案,这里有视频示例和代码框中的源代码
使用上下文API
import React from "react";
// create the context
export const Context = React.createContext();
// create the context provider, we are using use state to ensure that
// we get reactive values from the context...
export const TheProvider = ({ children }) => {
// the reactive values
const [sharedValue, setSharedValue] = React.useState({
value: "initial",
changedBy: "Admin"
});
// the store object
let state = {
sharedValue,
setSharedValue
};
// wrap the application in the provider with the initialized context
return <Context.Provider value={state}>{children}</Context.Provider>;
};
export default Context;在useReducer环境下使用减速器
const reducer = (state: IState, action: ActionType): IState => {
switch (action.type) {
case "update":
return { ...state, ...action.payload };
case "clear":
return { ...state, ...action.payload, value: "" };
default:
throw new Error();
}
};
const [state, dispatch] = React.useReducer(reducer, initialState);https://stackoverflow.com/questions/62236755
复制相似问题