javascript - 我如何在 react 中映射渲染状态?

标签 javascript reactjs

我正在尝试学习 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/

相关文章:

javascript - HTML 页面,隐藏的 div 出现

javascript - 将 NodeJs 与 React 结合使用

reactjs - 我如何访问React路由器2上的当前哈希位置?

javascript - 提取 URL 中的 React Router 状态

java - 当键是数字时解析 json 时出现解析错误

javascript - ngroute 后指令加载不正确

javascript - 将数组中的变量替换为循环中的数据

javascript - Stripe API 的结帐对话框是否允许比字符串更复杂的描述?

javascript - Reactjs 中的状态没有更新

javascript - ReactJS需要从外部类组件调用函数