我正在尝试通过react挂钩同步本地存储和状态,但是即使设置了setTimeout()也无法获得正确的值,
例如,我试图在数组中保存一个新键,并且如果我直接打印状态或本地存储,我仍然会得到先前的状态,但是如果在返回组件后打印状态,我得到正确的值,我该如何工作?
像这样,我仍然可以恢复以前的状态,
const onSave = () => {
setState(prevState => [...prevState, {...newState}])
localStorage.setItem('localState', JSON.stringify(state)) ;
console.log(JSON.parse(localStorage.getItem('localState'))) <-- //still getting the previous state :(
}
但是如果我做这样的事情,那么我会得到正确的值,但是我无法正确设置本地存储,或者我可以吗?
const App = (props) =>{
const onSave = () =>{
setState(prevState => [...prevState, {...newState}])
localStorage.setItem('localState', JSON.stringify(state)) ;
}
return(
<div>
{ console.log(JSON.parse(localStorage.getItem('localState'))) } <<-- correct state, wrong place
</div>
)
}
谢谢你们!
答案 0 :(得分:0)
setState
函数是异步的,因为您将立即将数据保存到本地存储中,所以它正在保存旧状态itslef
尝试将功能更改为
const onSave = () =>{
setState(prevState => [...prevState, {...newState}])
}
useEffect(() => {
localStorage.setItem('localState', JSON.stringify(state)) ;
console.log(JSON.parse(localStorage.getItem('localState')))
}, prevState)
答案 1 :(得分:0)
代码:
var cookieValue = document.getElementById("demo");
var value = cookieValue.getAttribute('value');
if(typeof(Storage)!=="undefined")
{
console.log(value);
localStorage.setItem("GetData" , value);
console.log(localStorage.getItem("GetData"));
}
function loading()
{
console.log("coming");
var allcookies = localStorage.getItem('GetData');
console.log(allcookies);
}