【问题标题】:Need help to save recent searches in localStorage - React/Redux需要帮助以在 localStorage 中保存最近的搜索 - React/Redux
【发布时间】:2018-10-02 22:50:08
【问题描述】:

我正在使用foursquare api 来搜索吃饭的地方。我想将用户最近的搜索保存在本地存储中,并在侧边栏中显示 10 个搜索。当用户点击它们时,它会将它们重定向到该搜索结果页面。有人可以指出正确的方向,即如何在 react/redux 架构中实现这一点吗?

如果您想查看应用程序,请点击这里的代码框链接。

https://codesandbox.io/s/koj4484zqo

【问题讨论】:

  • 我对此投了反对票,因为问题引用了一个不再存在的代码示例,从问题中获取上下文

标签: html reactjs local-storage


【解决方案1】:

您实际上不需要为此功能使用redux。您可以序列化您想要存储的数据,并在您想要使用它时将其对象化。下面是一个简单的例子。

class YourClass extends React.Component{
    constructor(props){
        super(props);

        this.onChangeHandler = this.onChangeHandler.bind(this);
        this.saveToStorage = this.saveToStorage.bind(this);
        this.recover = this.recover.bind(this);
    }

    componentDidMount(){
        //check for localStorage every time component mounts. You can also do this conditionally.
        this.recover();
    }

    recover(){
        //parse the localstorage value
        let data = JSON.parse(localStorage.getItem('history'));

        this.setState({history: data.history});
    }

    onChangeHandler(e){
        e.preventDefault();

        this.setState({input: e.target.value});
    }

    saveToStorage(){
        //local storage only takes in key value pair so you would have to serialize it.
        let history = this.state.history ? this.state.history : {history: []};

        history.history.push({text:this.state.input, link:'store linke here'});

        localStorage.setItem('history', JSON.stringify(history));
    }

    render(){
        return (
            <div>
                <input onChange={this.onChangeHandler}/>
                <Button onClick={this.saveToStorage}>
                    Save
                </Button>
                <div className="your-side-bar">
                    {this.state.history ? this.state.history.map((item) => {
                        return (
                            //render as state changes
                            <Link to={item.link}>{item.text}</Link>
                        )
                    }) : 'no history'}
                </div>
            </div>
        );
    }
}

我没有测试过代码,但你明白了。

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 1970-01-01
    • 2020-06-06
    • 2012-08-25
    • 2017-08-03
    • 2017-03-30
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多