![](/img/trans.png)
[英]Retrieving AND Displaying saved data from local storage inanother web page
[英]Local storage data not saved
更新:它的工作。 问题来自 useEffect
当我尝试“提交”特定任务时,本地存储中显示状态属性未更改。 我想知道我哪里出错了。 我试图用来更新本地存储的数据是 initialState.stuff。
这是我的 reducer.js 代码:
const reducer = (state,action)=>{
if(action.type ==="completed"){
//the relevant attributes to be changed
let temp = state.stuff.map((task)=>{
if(task.id === action.payload){
return {...task,status:status,enddate:enddate}
}
return task;
});
// the rest of the parts of this code is irrelevant
这是我的 context.js 代码:
import React, {useState,useContext,useEffect,useReducer} from "react"
import reducer from "./reducer";
const AppContext = React.createContext()
const initialState = {
stuff: null
}
const AppProvider = ({children}) =>{
const [tasks,setTasks] = useState([])
const [status,changeStatus] = useState("");
const [state,dispatch] = useReducer(reducer,initialState)
const complete = (id) =>{
dispatch({type:"completed",payload:id})
console.log("done", initialState.stuff)
setTasks(initialState.stuff)
}
const deleted = (id) =>{
dispatch({type:"deleted",payload:id})
}
const getLocalStorage = () =>{
state.stuff = localStorage.getItem("tasks")
if(state.stuff){
state.stuff = JSON.parse(state.stuff)
return JSON.parse(localStorage.getItem("tasks"))
}
else{
return []
}
}
const fetchData = async()=>{
setLoading(true)
setTasks(getLocalStorage());
setLoading(false);
}
useEffect(()=>{
fetchData()
},[])
useEffect(()=>{
localStorage.setItem("tasks",JSON.stringify(tasks))
},[tasks])
return <AppContext.Provider
value = {{
loading,
tasks,setTasks
}}>
{children}
</AppContext.Provider>
}
export const useGlobalContext = () =>{
return useContext(AppContext)
}
export {AppContext,AppProvider}
我认为您的代码中可能存在(我尚未完全阅读您的代码)变量冲突。 您可以尝试编写window.localStorage
而不是localStorage
并检查它是否解决了您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.