【问题标题】:Persist state in localStorage and retrieving state in componentDidMount在 localStorage 中保持状态并在 componentDidMount 中检索状态
【发布时间】:2019-08-01 07:49:47
【问题描述】:

当用户选择它并在 componentDidMount 方法中检索状态时,我试图将 Button 选项值的状态保留在 localStorage 中,但我得到一个空值。当用户导航回页面时,状态值应该在那里。谁能告诉我我的代码有什么问题?

代码::

import React, { Component } from "react";
import { Button } from "semantic-ui-react";
import { withRouter } from "react-router";
import Answers from "../Answers/Answers";

class Section extends Component {
    state = {
        que1: "",
        que2: "",
        que3: ""
    };

    handleClick = event => {
        this.setState(
            {
                que1: event.target.attributes.getNamedItem("data-key").value
            }

        ),
            () => {
                localStorage.setItem("que1", que1);
                console.log(this.state.que1);
            }
    };

    handleClick2 = event => {
        this.setState(
            {
                que2: event.target.attributes.getNamedItem("data-key").value
            }
        ),
            () => {
                localStorage.setItem("que2", que2);
                console.log(this.state.que2);
            }
    };

    handleClick3 = event => {
        this.setState(
            {
                que3: event.target.attributes.getNamedItem("data-key").value
            }
        ),
            () => {
                localStorage.setItem("que3", que3);
                console.log(this.state.que3);
            }
    };

    componentDidMount() {
        this.setState({
            que1: localStorage.getItem("que1"),
            que2: localStorage.getItem("que2"),
            que3: localStorage.getItem("que3")
        });
    }

    render() {
        console.log(this.state);

        let styles = {
            width: '50%',
            margin: '0 auto',
            marginBottom: '15px'
        }
        const { history } = this.props;
        const { que1, que2, que3 } = this.state;
        return (
            <>
                <p>1. I was stressed with my nerves on edge.</p>
                <Button.Group widths="5" onClick={this.handleClick} style={styles}>
                    <Answers selected={this.state.que1} style={{ backgroundColor: 'red' }} />
                </Button.Group>
                {` `}
                <p>2. I lost hope and wanted to give up when something went wrong.</p>
                <Button.Group widths="5" onClick={this.handleClick2} style={styles}>
                    <Answers selected={this.state.que2} style={{ backgroundColor: 'red' }} />
                </Button.Group>
                {` `}
                <p>3. I feel very satisfied with the way I look and act</p>
                <Button.Group widths="5" onClick={this.handleClick3} style={styles}>
                    <Answers selected={this.state.que3} style={{ backgroundColor: 'red' }} />
                </Button.Group>
                <p />
                {` `}
                <Button
                    disabled={!que1 || !que2 || !que3}
                    onClick={() => history.push("/section2", [this.state])}
                >
                    NEXT
        </Button>
            </>
        );
    }
}

export default withRouter(Section);

输出 ::

【问题讨论】:

    标签: reactjs local-storage


    【解决方案1】:

    在您的 onclick 处理程序中,您有:

        handleClick2 = event => {
            this.setState(
                {
                    que2: event.target.attributes.getNamedItem("data-key").value
                }
            ),
                () => {
                    localStorage.setItem("que2", que2);
                    console.log(this.state.que2);
                }
        };
    

    在 setState 回调中,您需要将其更改为(您记录了正确的值,但没有正确存储它):

    localStorage.setItem("que2", this.state.que2);
    

    【讨论】:

    • 当用户单击下一个按钮并返回此页面时,状态应保持
    • 它将“持续(某种)”。你的 console.log 显示什么?你确定你正确地填充了这个值吗?在很短的时间内,当您向后导航时,您将在 state.que 中看到一个空值(直到 setState 完成)。例如,如果您添加一个 componentDidUpdate 函数并记录状态,您将看到初始的空状态,然后是从 localStorage 分配的状态。
    【解决方案2】:

    这不应该是 React 的做法。你应该在这里实现一个 redux 工作流,这将帮助你在页面之间导航时持久化数据。请参阅https://redux.js.org/basics/usage-with-react。当你点击返回按钮时,你可以从 redux 存储中取回值。

    现在,根据您的情况将其更改为

    handleClick(e) => {
        const value = event.target.attributes.getNamedItem('data-key').value;
        this.setState({que1 : value});
        localStorage.setItem('que1', value);
    };
    

    在构造函数中

    constructor() {
        this.state = {
            que1 : localStorage.getItem('que1') ? localStorage.getItem('que1') : ''
        };
    };
    

    但完全不推荐使用上述解决方案。继续使用 redux 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      相关资源
      最近更新 更多