【发布时间】:2022-01-15 17:25:42
【问题描述】:
我有一个 react 元素 testReactElement 并希望在屏幕上显示它,即使在用户关闭选项卡并再次打开它之后,他们应该会发现仍然显示相同的数据,所以我将它放在 localStorage 上,并且要将 react 元素添加到 localStorage 我首先应该使用 JSON.stringify() 对其进行字符串化,并且它成功存储在 localstorage 中,当我想从本地存储中检索它并显示它时,我使用 JSON.parse()。
import './App.css';
let testReactElement = <div>
<h1>this is the title of the react element</h1>
<p>This is the content of the react element</p>
</div>
localStorage.setItem('element',JSON.stringify(testReactElement))
function App() {
return (
<div className="App">
{JSON.parse(localStorage.getItem('element'))}
</div>
);
}
export default App;
问题是 JSON.parse() 返回一个 javascript 对象,看起来与我最初添加到 localStorage 的 react 元素相似但不一样,并且新返回的对象缺少一些键,因此 react 不会将其识别为一个反应元素,并抛出以下错误 Error: Objects are not valid as a React child (found: object with keys {type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead.
当我尝试将原始反应元素与字符串化的元素进行比较时,我发现在字符串化之后,反应元素缺少'$$typeof'符号键,这导致反应不将其识别为反应元素并且只看到它作为一个普通的 JS 对象,因此抛出一个错误。经过一番谷歌搜索,我发现这是因为当我们尝试 JSON.stringify(symbol) 时它返回undefined。
那么如何将 react 元素放入 localstorage 中,然后在我最初输入时将其取回,以便将其显示在屏幕上?
【问题讨论】:
-
JSON.stringify不存储某些值(函数,未定义),因此这不起作用。您最好存储组件的 state 副本,然后相应地恢复组件。
标签: javascript reactjs json