我正在尝试学习 React,但遇到了一些问题。
当我尝试映射数组状态时,我收到“无法读取 null 的属性‘map’”。
我如何确保在渲染之前设置状态?
state = {
array: []
};
componentDidMount() {
this.setState({ array: JSON.parse(localStorage.getItem('session')) });
}
render() {
const displayArray = this.state.array.map((item, index) => {
return <p key={index}>{item}</p>
});
return (
<div>{displayArray}</div>
);
}
最佳答案
如果本地存储中没有存储键'session'
的值,您将返回null
。将其传递到 JSON.parse
中,它将被转换为 "null"
然后进行解析(再次给出 null
)。然后,您可以将其用作数组值。
要处理这种情况,请在 key 不存在时提供默认值:
this.setState({ array: JSON.parse(localStorage.getItem('session')) || [] });
// ---------------------------------------------------------------^^^^^^
仍然假设如果存储了一个值,它将解析为一个数组。如果可能存储了非数组值,您需要进行更全面的检查:
let array;
try {
array = JSON.parse(localStorage.getItem('session'));
} catch (e) {
}
this.setState({array: Array.isArray(array) ? array : []});
...或类似的。
<小时/>旁注:由于从本地存储检索是同步的,因此无需等到 componentDidMount
来执行此操作。只需在最初创建状态时执行此操作即可:
state = {
array: JSON.parse(localStorage.getItem('session')) || []
};
(如有必要,再次进行更全面的检查。)
如果它是异步的,您需要等待,但由于它是同步的,因此没有必要,并且提前执行可以避免不必要的渲染。
<小时/>旁注 2:参见 the documentation on keys为什么通常不建议使用索引作为键:
We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
关于javascript - 我如何在 react 中映射渲染状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52384313/