리액트 라우터를 통해 설정된 경로에서 Redx Store에 액세스하는 방법
리액트 라우터의 리액트 라우터의onEnter핸들러: 제한된 루트를 입력할 때 사용자에게 인증을 요구합니다.
지금까지의 나의routes.js파일은 다음과 같습니다.
import React from 'react';
import { Route, IndexRoute } from 'react-router';
export default (
    <Route   path="/"         component={App}>
      <IndexRoute             component={Landing} />
      <Route path="learn"     component={Learn} />
      <Route path="about"     component={About} />
      <Route path="downloads" component={Downloads} onEnter={requireAuth} />
    </Route>
)
 
이상적으로, 나는 내 것을 원한다.requireAuth저장소와 현재 상태에 액세스할 수 있는 축소 작업으로서 다음과 같이 작동합니다.store.dispatch(requireAuth()).
유감스럽게도 저는 이 파일의 스토어에 액세스할 수 없습니다.이 경우 원하는 액션에 액세스하기 위해 실제로 사용할 수 있다고 생각하지 않습니다.나도 못 참겠어import store이것은 앱이 처음 로드될 때 정의되지 않기 때문에 스토어가 생성된 파일에서 확인할 수 있습니다. 
이를 위한 가장 쉬운 방법은 (루트를 직접 반환하는 것이 아니라) 경로를 반환하는 함수에 스토어를 전달하는 것입니다.이렇게 하면 다음 위치에 있는 스토어에 액세스할 수 있습니다.onEnter및 기타 리액트라우터 방식.
경로의 경우:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
export const getRoutes = (store) => (
  const authRequired = (nextState, replaceState) => {
    // Now you can access the store object here.
    const state = store.getState();
    if (!state.user.isAuthenticated) {
      // Not authenticated, redirect to login.
      replaceState({ nextPathname: nextState.location.pathname }, '/login');
    }
  };
  return (
    <Route   path="/"         component={App}>
      <IndexRoute             component={Landing} />
      <Route path="learn"     component={Learn} />
      <Route path="about"     component={About} />
      <Route path="downloads" component={Downloads} onEnter={authRequired} />
    </Route>
  );
)
 
그런 다음 메인 컴포넌트를 업데이트하여getRoutes함수, 스토어 내 전달:
<Provider store={ store }>
  <Router history={ history }>
    { getRoutes(store) }
  </Router>
</Provider>
 
액션을 디스패치하는 경우requireAuth, 다음과 같이 함수를 쓸 수 있습니다.
const authRequired = (nextState, replaceState, callback) => {
  store.dispatch(requireAuth())  // Assume this action returns a promise
    .then(() => {
      const state = store.getState();
      if (!state.user.isAuthenticated) {
        // Not authenticated, redirect to login.
        replaceState({ nextPathname: nextState.location.pathname }, '/login');
      }
      // All ok
      callback();
    });
};
 
이게 도움이 됐으면 좋겠다.
필요한 경우 다음과 같이 route.js 라고 쓸 수 있습니다.
var requireAuth = (store, nextState, replace) => {
  console.log("store: ", store);
  //now you have access to the store in the onEnter hook!
}
export default (store) => {
  return (
      <Route path="/"           component={App}>
        <IndexRoute             component={Landing} />
        <Route path="learn"     component={Learn} />
        <Route path="about"     component={About} />
        <Route path="downloads" component={Downloads} onEnter={requireAuth.bind(this, store)} />
      </Route>
    );
);
 
이 고문서에서 다룰 수 있는 예를 준비했습니다.
인증을 처리하기 위해 액션을 트리거하는 것이 좋은 생각인지 잘 모르겠습니다.개인적으로는 인증을 다른 방법으로 처리하는 것을 선호합니다.
를 사용하는 대신onEnter후크, 저는 랩 기능을 사용합니다.블로그의 관리 섹션을 보호하고 싶기 때문에AdminContainer기능이 있는 경로의 구성 요소,requireAuthentication, 이하를 참조해 주세요.
export default (store, history) => {
        return (
            <Router history={history}>
                <Route path="/" component={App}>
                    { /* Home (main) route */ }
                    <IndexRoute component={HomeContainer}/>
                    <Route path="post/:slug" component={PostPage}/>
                    { /* <Route path="*" component={NotFound} status={404} /> */ }
                </Route>
                <Route path="/admin" component={requireAuthentication(AdminContainer)}>
                    <IndexRoute component={PostList}/>
                    <Route path=":slug/edit" component={PostEditor}/>
                    <Route path="add" component={PostEditor}/>
                </Route>
                <Route path="/login" component={Login}/>
            </Router>
        );
    };
 
requireAuthentication이 함수는
- 사용자가 인증되면 랩된 컴포넌트를 렌더링합니다.
 - 그렇지 않으면 로 리다이렉트 됩니다.
Login 
이하를 참조해 주세요.
export default function requireAuthentication(Component) {
    class AuthenticatedComponent extends React.Component {
        componentWillMount () {
            this.checkAuth();
        }
        componentWillReceiveProps (nextProps) {
            this.checkAuth();
        }
        checkAuth () {
            if (!this.props.isAuthenticated) {
                let redirectAfterLogin = this.props.location.pathname;
                this.context.router.replace({pathname: '/login', state: {redirectAfterLogin: redirectAfterLogin}});
            }
        }
        render () {
            return (
                <div>
                    {this.props.isAuthenticated === true
                        ? <Component {...this.props}/>
                        : null
                    }
                </div>
            )
        }
    }
    const mapStateToProps = (state) => ({
        isAuthenticated: state.blog.get('isAuthenticated')
    });
    AuthenticatedComponent.contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    return connect(mapStateToProps)(AuthenticatedComponent);
}
 
또한.requireAuthentication모든 루트를 보호한다./admin원하는 장소에서 재사용할 수 있습니다.
시간이 지나면서 많은 것이 바뀌었다. onEnter더 이상 존재하지 않는다react-router-4
다음은 제 실제 프로젝트의 참고 자료입니다.
export const getRoutes = (store) => {
  const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkIfAuthed(store) ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login'
        }}/>
      )
    )}/>
  )
  return (
    <Router>
      <div>
        <PrivateRoute exact path="/" component={Home}/>
        <Route path="/login" component={Login} />
      </div>
    </Router>
  )
} 
 위의 몇 가지 제안을 시도해 본 결과, 업데이트로 당신의 스토어 상태를 추적하는 가장 좋은 방법은 React-Redux를 사용하는 것임을 알게 되었습니다.useSelector기본적으로 기능 컴포넌트를 스토어에 연결하는 기능.
import * as React from "react";
import {Redirect, Route, Switch} from "react-router";
import {Provider, useSelector} from "react-redux";
import { createBrowserHistory } from "history";
// Your imports
import {IApplicationState,} from "./store/store";
import {Login} from "./routes/login/login.component";
import {getToken} from "./store/helpers/httpHelpers";
function handleRedirect() {
    if(!getToken()) {
        return <Redirect to="/login"/>;
    }
}
const restricted = (Component: _ComponentType, isLoggedIn: boolean) => {
   // Don't redirect here if there is a token in localStorage.
   // This is happening when we are on a restricted route and the user
   // refreshes & the isLoggedIn state hasn't been updated yet.
    return !isLoggedIn ? (
        () => handleRedirect()
    ) : () => <Route component={Component}/>
};
const AuthenticateRoutes = () => {
    const isLoggedIn = useSelector((state: IApplicationState) => state.auth.isLoggedIn);
    return (
        <Switch>
            <Route path="/login" component={Login} />
            <Route path="/downloads" render={restricted(Download, isLoggedIn)} />
        </Switch>
    );
};
export function App() {
    return (
        <Provider store={store}>
            <>
                <Router history={createBrowserHistory()}>
                    <AuthenticateRoutes />
                </Router>
            </>
        </Provider>
    );
}
언급URL : https://stackoverflow.com/questions/35849970/accessing-redux-store-from-routes-set-up-via-react-router
'programing' 카테고리의 다른 글
| jquery의 ajax 함수에서 비동기 false 및 비동기 true를 사용하는 경우 (0) | 2023.03.17 | 
|---|---|
| 잘못된 구성 개체입니다.API 스키마와 일치하지 않는 구성 개체를 사용하여 웹 팩이 초기화되었습니다. (0) | 2023.03.17 | 
| &을 포함하는 문자열을 삽입하는 방법 (0) | 2023.03.17 | 
| 봄 부츠에 백합 사투리 어떻게 넣어요? (0) | 2023.03.17 | 
| AngularJ는 루트 변경 시 보류 중인 $http 요구를 모두 중단합니다. (0) | 2023.03.17 |