Polymer-redux:如何使用聚合物在redux中存储数据?

时间:2018-03-28 11:27:05

标签: redux polymer polymer-2.x

我用redux创建了聚合物应用程序。 redux工作正常,它存储数据。但是当我重新加载页面时,它会刷新数据。如何存储下一页的数据?我想将数据存储在redux中,就像本地存储一样。任何人都可以帮助我吗?

提前致谢。

这里是我的redux代码

<link rel="import" href="../../bower_components/polymer-redux/polymer-redux.html">
<script src="../../node_modules/redux/dist/redux.min.js"></script>

<script>
    const initialState = {
        user: {"username":"admin", "password":123},
        isLoggedIn: false,
        friends : ["Mahadev"]
    };

    const reducer = (state, action) => {
        if(!state) return initialState;
        switch(action.type){
            case "UPDATE_LOGGEDIN":
                state.isLoggedIn = action.isLogin;
                return Object.assign({}, state, {isLoggedIn:state.isLoggedIn});
            case "ADD_FRIEND":
                let friends = state.friends.slice(0);
                friends.push(action.friend);
                return Object.assign({}, state, {friends:friends});
            default:
                return state;
        }
    }

    const store = Redux.createStore(reducer, initialState);
    const ReduxMixin = PolymerRedux(store);
</script>

聚合物登录页面脚本

<script>
    class LoginPage extends ReduxMixin(Polymer.Element){
        static get is(){ return "login-page"; }

        static get properties(){
            return {
                user: {
                    type: Array,
                    statePath: "user"
                }
            };
        }

        static get actions(){
            return {
                loggenIn : function(isLogin){
                    return {
                        type: "UPDATE_LOGGEDIN",
                        isLogin: isLogin
                    };
                }
            };
        }

        _doLogin(){
            let username = this.$.username;
            let userpass = this.$.userpass;
            if(username.value && userpass.value) {
                if ((username.value == this.user.username) && (userpass.value == this.user.password)) {
                    this.dispatch("loggenIn", true);
                    window.history.pushState({}, null, '/home-page');
                    window.location.reload(true);
                } else {
                    alert("Invalid username or password !");
                }
            }
        }
    }

    window.customElements.define(LoginPage.is, LoginPage);
</script>

1 个答案:

答案 0 :(得分:0)

如果您正在制作SPA(单页应用程序),则无需存储数据。您可以使用PolymerElements app-route在SPA内进行路由。

如果您确实想使用LocalStorage,则可以使用LocalStorage.getItem(key)检索值,使用LocalStorage.setItem(key,value)来设置值。