在localStorage中保持状态,在componentDidMount中恢复状态

时间:2019-03-11 02:09:27

标签: reactjs local-storage

当用户选择Button选项值的状态并在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);

输出::

enter image description here

2 个答案:

答案 0 :(得分:0)

在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);

答案 1 :(得分:0)

这不应该是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方法。