带有Redux的专用路由并响应路由器

时间:2020-05-08 13:05:25

标签: reactjs redux react-router express-session

我有一个带有身份验证和私有路由的简单应用程序,如果用户有令牌,后端已经准备好并且可以正常工作,我想从服务器获取数据,并且我登录后在Redux中有关于用户的数据,但是我不知道如何用刷新页面来处理,我应该在哪里采取行动去采取行动?如果我在privateRoute.js中进行操作,它的工作方式很奇怪,我想给服务器打电话,但是我做了3-4次。

这是我的未调用sessionActions的组件,sessionActions应该更新loginIn,用户将转到/ login页面

PrivateRoute

import React, { useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import  sessionAction  from '../store/actions/sessionAction';

const PrivateRoute = ({ component: Component, ...rest }) => {
  const { path, dispatch, loggedIn } = rest;
  });

  return (
    <Route
      path={path}
      render={(props) => (loggedIn ? <Component {...props} />
     <Component {...props}/>
        : (<Redirect to="/login" />))}
    />
  );
};

PrivateRoute.propTypes = {
  component: PropTypes.func.isRequired,
};
export default PrivateRoute;

sessionAction

const sessionAction = (path) => (dispatch) => {
  return sessionServices(path)
    .then((response) => {
      console.log(response);
      const { data } = response;
      if (!data.error) {
        dispatch(success(data));
      }
      dispatch(failure(data.error.text));
    })
    .catch((error) => error);
};

sessionService

import axios from 'axios';

axios.defaults.withCredentials = true;

const sessionServices = (path) => axios({
  method: 'post',
  url: `http://localhost:4000/api/pages${path}`,
})
  .then((response) => response)
  .catch((error) => console.log(error));

export default sessionServices;

0 个答案:

没有答案