gpt4 book ai didi

javascript - 刷新页面后如何正确保存 Redux 状态?

转载 作者:行者123 更新时间:2023-12-04 04:09:50 26 4
gpt4 key购买 nike

请求代码:

export class LogInContainer extends Component {

submit = (values) => {
const { mutate } = this.props;
mutate({
variables: {
email: values.email,
password: values.password,
},
})
.then((res) => {
const token = res.data.login.token;
localStorage.setItem("token", token);
const user = res.data.login.user;
const { logIn } = this.props;
logIn(user);
this.props.history.push("/pages/processes");
})
.catch((error) => {
const errorMessage = error.message;
const { logInError } = this.props;
logInError(errorMessage);
});
};

render() {
const { error, logInCleanError } = this.props;
return (
<LogIn
onSubmit={this.submit}
errorMessage={error}
logInCleanError={logInCleanError}
/>
);
}
}

export default compose(
graphql(LOG_IN),
withRouter,
connect(({ errors }) => ({ error: errors.log_in_error }), {
logInError,
logInCleanError,
logIn,
})
)(LogInContainer);

reducer 代码:
const initialState = {
user: {
id: "",
firstName: "",
secondName: "",
email: "",
isAuth: localStorage.getItem('token') ? true : false,
},
};

export const userReducer = (state = initialState, { type, user }) => {
switch (type) {
case LOG_IN:
return {
...state,
user: {
id: user.id,
firstName: user.firstName,
secondName: user.secondName,
email: user.email,
isAuth: true,
},
};
case CURRENT_USER:
return {
...state,
user: {
id: user.id,
firstName: user.firstName,
secondName: user.secondName,
email: user.email,
isAuth: true,
},
};
case LOG_OUT:
return {
...state,
user: {
id: "",
firstName: "",
secondName: "",
email: "",
isAuth: false,
},
};
default:
return state;
}
};

我保存 JWT 并将其放在每个请求的 header 中,例如:
const client = new ApolloClient({
uri: "http://localhost:4000/api",
request: (operation) => {
const token = localStorage.getItem("token");
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : "",
},
});
},
});

我保护我的路由器,例如:
const App = ({ authorized }) => {
return (
<Switch>
{!authorized ? (
<Route path="/auth">
<Auth />
</Route>
) : (
<Route path="/pages">
<Pages />
</Route>
)}
<Redirect from="/" to="/auth/login" />
</Switch>
);
};

export default App;

刷新正在登录的页面后,我并没有丢失 JWT 并留在系统中,但是我丢失了需要在页面上显示的用户名、第二名等的 redux 状态。那么在没有像 redux-persist 或其他插件的情况下保存 redux 状态的正确方法是什么

最佳答案

🎈 马上

做这个:

const initialState = {
user: {
id: localStorage.getItem('id') || '',
firstName: localStorage.getItem('firstName') || '',
secondName: localStorage.getItem('secondName') || '',
email: localStorage.getItem('email') || '',
isAuth: localStorage.getItem('token') ? true : false,
},
}

📿 有点复杂但可扩展的方式

创建 middleware这将服务于与应用程序持久状态相关的所有内容。在那里,您可以将数据保存到 localStorage、cookie 或 IndexedDB。中间件,我们称之为 LocalStoreMiddleware 将监听你的 redux reducer 所做的相同操作,当一个操作将被分派(dispatch)时,无论在哪里以及由谁(组件、Saga、Socket)每个中间件将完成其负责的工作,reducers 将更新 redux 存储, LocalStoreMiddleware 会将数据保存到 localStorage、cookie、indexDB 等。

优势
  • 没有紧密的依赖关系
  • 易于扩展
  • 一地一域业务逻辑
  • 你让纳尼亚世界的一些 Sprite 开心

  • 创建一个文件,您将在其中存储与持久数据相关的函数
    // local-store-resolvers.js
    import {on} from './local-store-middleware.js'

    function saveToken(action, state) {
    localStorage.setItem('token', JSON.stringify(state.token));
    }

    function saveUsername(action) {
    localStorage.setItem('username', JSON.stringify(action.username));
    }

    export default [
    on(AUTHORIZATION, saveToken),
    on(USERNAME_CHANGED, saveUsername),
    ]

    中间件厂
    // local-store-middleware.js
    export const on = (actionType, resolver) => (action, state) => (
    actionType === action.type && resolver(action, state)
    )

    const createLocalStoreMiddleware = resolvers => store => next => action => {
    resolvers.forEach(
    resolver => resolver(action, store.getState())
    )
    return next(action)
    }

    export default createLocalStoreMiddleware

    Redux 商店
    // src/store/index.js - your main file where you create redux store
    import createLocalStoreMiddleware from './local-store-middleware.js'
    import resolvers from './local-store-resolvers.js'

    const localStore = createLocalStoreMiddleware(resolvers)

    const store = createStore(
    combineReducers({users, someOtherReducer}),
    applyMiddleware(localStore), // if you have more middlewares use compose
    )

    export default store

    关于javascript - 刷新页面后如何正确保存 Redux 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61921005/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com