我正在通过localStorage在我的React应用程序中保存状态
const [items, setItem] = useState(() => {
let itemsString = window.localStorage.getItem('items');
if (itemsString) {
try {
return JSON.parse(itemsString);
} catch (e) {
console.error(e);
return [];
}
} else {
return [];
}
})
当我对itemsString
执行JSON.parse()
时,状态中的日期已被转换为UTC(因为它是字符串/本地存储)
我该如何对我的状态执行JSON.parse()
并重新初始化日期字符串为对象?
例如,不要返回2019-07-19T00:28:03.058Z,而是返回Thu Jul 18 2019 20:28:03 GMT-0400 (Eastern Daylight Time)
通过Aaron的建议,我想出了以下解决方案。
存储旧状态。映射状态数组,创建新的空对象并将每个属性存储在其中,存储日期,将日期转换为字符串,并将其传递到新的Date对象中,在页面刷新时实例化回一个日期对象。
const [items, setItem] = useState(() => {
let itemsString = window.localStorage.getItem('items');
if (itemsString) {
try {
const oldState = JSON.parse(itemsString);
const newState = oldState.map(item => {
const date = item.date;
const container = {}
container.id = item.id
container.item = item.item
container.date = new Date(date.toString())
container.cost = item.cost
container.type = item.type
return container;
})
return newState;
} catch (e) {
console.error(e);
return [];
}
} else {
return [];
}
})
try { const object = JSON.parse(itemsString); const newState = {...object, date: new Date(object.date)} return newState }
- gwar9JSON.parse(itemsString)
might return something like[{…}] 0: {id: "2019-07-19T01:45:29.929Z", item: "Couch", date: "2019-07-19T01:45:21.376Z", cost: "78", type: "expense"} length: 1 __proto__: Array(0)
- gwar9