Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 刷新页面后如何正确保存Redux状态?_Javascript_Reactjs_Redux_Apollo Client - Fatal编程技术网

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

Javascript 刷新页面后如何正确保存Redux状态?,javascript,reactjs,redux,apollo-client,Javascript,Reactjs,Redux,Apollo Client,请求代码: export class LogInContainer extends Component { submit = (values) => { const { mutate } = this.props; mutate({ variables: { email: values.email, password: values.password, }, }) .then((res) =&

请求代码:

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);
我保存JWT并将其放入每个请求的标题中,如:

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;
const-App=({authorized})=>{
返回(
{!授权(
) : (
)}
);
};
导出默认应用程序;
在刷新登录的页面后,我不会丢失JWT并留在系统中,但会丢失带有用户名字、第二名字等的redux状态,我需要在页面上显示这些信息。那么,在没有redux persist或其他插件的情况下,保存redux状态的正确方法是什么呢

localStorage.setItem('token', token);
加载应用程序时,检查是否设置了令牌,如果设置了令牌,则从localStorage获取信息

localStorage.getItem('token');
您还可以保存用户信息:

localStorage.setItem('user', JSON.stringify(userInfo));
并使用JSON.parse获取它。

因为您应该在
商店的subscribe
方法中使用
本地存储

store.subscribe(() => {
  // persist your state
})
创建存储之前,请阅读这些持久化部分:

如果您使用
combineReducers()
您会注意到没有 接收到的状态将使用默认的
状态正常“启动”
参数值。这很方便

建议您取消订阅方的订阅,这样您就不会写了 到本地存储的速度太快,否则会出现性能问题

最后,您可以创建一个中间件,将其封装为 另一种选择,但我会从订阅者开始,因为这是一个更简单的方法 解决方案,并做好工作


即使在刷新之后也可以保存redux状态的干净整洁的解决方案是redux persist

它就像一个符咒


查看
redux persist
store.subscribe(() => {
  // persist your state
})
const persistedState = // ...
const store = createStore(reducer, persistedState)