programing

리액트 라우터 v4의 이력을 얻는 방법

instargram 2023. 3. 3. 16:50
반응형

리액트 라우터 v4의 이력을 얻는 방법

React-Router v3에서 v4로 마이그레이션하는 데 약간의 문제가 있습니다. v3에서는 다음을 어디에서나 수행할 수 있었습니다.

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');

v4에서 이를 실현하려면 어떻게 해야 합니까?

내가 할 수 있다는 걸 알아withRouter컴포넌트에 있을 때 react context 또는 event router foops를 선택합니다.단, 저는 그렇지 않습니다.

v4에서 Navigating Outside Of Components와 동등한 기능을 찾고 있습니다.

이 모듈을 사용하여 이 모듈을 export 할 수 있습니다.history물건.그런 다음 프로젝트 전체에서 해당 개체를 가져옵니다.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})

그런 다음 내장 라우터 중 하나를 사용하는 대신<Router>요소.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')

이거 돼!https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

다른 컴포넌트로 이동하기 위해 이력 오브젝트만 필요한 경우 이 답변을 기반으로 합니다.

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

당신이 할 수 있는 것은 수용된 답변에 대한 유사성입니다.react그리고.react-router그 자체로서history파일 내에서 범위를 지정한 후 내보낼 수 있는 객체입니다.

history.disclosing

import React from 'react';
import { withRouter } from 'react-router';

// variable which will point to react-router history
let globalHistory = null;

// component which we will mount on top of the app
class Spy extends React.Component {
  constructor(props) {
    super(props)
    globalHistory = props.history; 
  }

  componentDidUpdate() {
    globalHistory = this.props.history;
  }

  render(){
    return null;
  }
}

export const GlobalHistory = withRouter(Spy);

// export react-router history
export default function getHistory() {    
  return globalHistory;
}

그런 다음 컴포넌트를 Import하여 기록 변수를 초기화합니다.

import { BrowserRouter } from 'react-router-dom';
import { GlobalHistory } from './history';

function render() {
  ReactDOM.render(
    <BrowserRouter>
        <div>
            <GlobalHistory />
            //.....
        </div>
    </BrowserRouter>
    document.getElementById('app'),
  );
}

그런 다음 앱이 마운트되면 앱으로 가져올 수 있습니다.

import getHistory from './history'; 

export const goToPage = () => (dispatch) => {
  dispatch({ type: GO_TO_SUCCESS_PAGE });
  getHistory().push('/success'); // at this point component probably has been mounted and we can safely get `history`
};

나는 그것을 할 수 있는 패키지와 npm 패키지도 만들었다.

redux 및 redux-thunk를 사용하는 경우 가장 좋은 솔루션은 react-router-redux를 사용하는 것입니다.

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))

몇 가지 설정을 실시하려면 , 문서를 참조하는 것이 중요합니다.

App.js의 경우

 import {useHistory } from "react-router-dom";

 const TheContext = React.createContext(null);

 const App = () => {
   const history = useHistory();

   <TheContext.Provider value={{ history, user }}>

    <Switch>
        <Route exact path="/" render={(props) => <Home {...props} />} />
        <Route
          exact
          path="/sign-up"
          render={(props) => <SignUp {...props} setUser={setUser} />}
        /> ...

다음으로 자 컴포넌트:

const Welcome = () => {
    
    const {user, history} = React.useContext(TheContext); 
    ....

특정의 경우react-router를 사용하는 것은 유효한 경우 시나리오입니다.

class MyComponent extends React.Component {
  props: PropsType;

  static contextTypes = {
    router: PropTypes.object
  };

  render () {
    this.context.router;
  }
}

라우터 컨텍스트를 통해 이력의 인스턴스에 액세스할 수 있습니다.this.context.router.history.

언급URL : https://stackoverflow.com/questions/42672842/how-to-get-history-on-react-router-v4

반응형