在将所有状态转换为上下文之前的工作代码:
App.js
function App() {
const [reptile, setReptile] = useState(function () {
const storedValue = localStorage.getItem("reptiles");
return JSON.parse(storedValue);
})...
...useEffect(
function () {
localStorage.setItem("reptiles", JSON.stringify(reptile));
},
[reptile]
);
字符串
我的当前代码:
Context.js
const ReptileContext = createContext();
function ReptileProvider({ children }) {
const [reptile, setReptile] = useState(function () {
const storedValue = localStorage.getItem("reptiles");
return JSON.parse(storedValue);
});
const [daysFed, setDaysFed] = useState("");
const [displayForm, setDisplayForm] = useState(false);
const [displayList, setDisplayList] = useState(true);
const [displayReptile, setDisplayReptile] = useState(false);
const [selectedReptile, setSelectedReptile] = useState(null);
const [today, setToday] = useState(null);
const [reptileType, setReptileType] = useState("");
const [reptileName, setReptileName] = useState("");
const [notes, setNotes] = useState("");
function handleAddReptile(reptile) {
setReptile((reptiles) => [...reptiles, reptile]);
}
function handleDeleteReptile(reptileId) {
setReptile((reptiles) => reptiles.filter((rep) => rep.id !== reptileId));
}
function handleSelection(reptileId) {
setSelectedReptile(reptileId);
setDisplayList(false);
setDisplayReptile(true);
}
function handleBack() {
setDisplayReptile(false);
setDisplayList(true);
}
return (
<ReptileContext.Provider
value={
(reptile,
reptileType,
setReptileType,
reptileName,
setReptileName,
notes,
setNotes,
daysFed,
setDaysFed,
displayForm,
setDisplayForm,
displayList,
setDisplayList,
displayReptile,
setDisplayReptile,
selectedReptile,
setSelectedReptile,
today,
setToday,
handleAddReptile,
handleDeleteReptile,
handleSelection,
handleBack)
}
>
{children}
</ReptileContext.Provider>
);
}
function useReptile() {
const context = useContext(ReptileContext);
if (context === undefined)
throw new Error("PostContext was used outside of the PostProvider");
return context;
}
export { ReptileProvider, useReptile };
型
App.js
function App() {
const { displayForm, displayList, displayReptile, selectedReptile, reptile } =
useReptile();
useEffect(
function () {
if (!reptile) return;
localStorage.setItem("reptiles", JSON.stringify(reptile));
},
[reptile]
);
型
index.js
<ReptileProvider>
<App />
</ReptileProvider>
型
我在加载时收到一个错误,内容为“JSON.parse:JSON数据的第1行第1列出现意外字符”。我相信这个问题与useEffect钩子的位置直接相关,但我不完全确定。任何帮助将不胜感激,谢谢!
1条答案
按热度按时间a11xaf1n1#
我认为问题不在于
useEffect
钩子,而在于将值传递给ReptileContext.Provider
的方式。使用圆括号而不是花括号,这意味着传递的是单个表达式而不是对象。这可能会导致JSON.parse
在尝试读取存储值时失败。字符串