我是一名新的React开发人员,在我的应用程序中实现了全局状态。我使用带有上下文API的useReducer来缓存表单搜索数据,但是我觉得我使用的reducer错误,即使它可以工作。在调用 dispatchSearchData 之前,我正在准备有效负载,而不是直接在reducer中完成它:
import React, { createContext, useReducer, useMemo, useEffect } from "react";
const initialData = {
from: "",
to: "",
date_go: "",
date_back: "",
passengers: "",
};
const dataReducer = (searchData, newData) => {
if (newData === null) {
localStorage.removeItem("currentSearchData");
return initialData;
}
return { ...searchData, ...newData };
};
const localData = JSON.parse(localStorage.getItem("currentSearchData"));
export const SearchDataContext = createContext({});
export const SearchDataProvider = (props) => {
const [searchData, dispatchSearchData] = useReducer(dataReducer, localData || initialData);
const searchDataValue = useMemo(
() => ({
searchData,
setSearchData,
}),
[searchData, setSearchData],
);
useEffect(() => {
localStorage.setItem("currentSearchData", JSON.stringify(searchData));
}, [searchData]);
return <SearchDataContext.Provider value={searchDataValue}>{props.children}</SearchDataContext.Provider>;
};
调用它的示例:
let search = (e) => {
e.preventDefault();
dispatchSearchData(formData);
setServiceData(null);
}