需要帮助来保存localStorage中最近的搜索 - React / Redux

时间:2018-04-22 23:52:05

标签: html5 reactjs local-storage

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

如果您想查看该应用,请参阅以下代码链接。

https://codesandbox.io/s/koj4484zqo

1 个答案:

答案 0 :(得分: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>
        );
    }
}

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