etc./StackOverFlow

React 라우터를 사용하여 프로그래밍 방식으로 탐색

청렴결백한 만능 재주꾼 2021. 12. 29. 03:38
반응형

질문자 :George Mauer


react-router 를 사용하면 Link 요소를 사용하여 기본적으로 반응 라우터에서 처리되는 링크를 만들 수 있습니다.

내부적으로 this.context.transitionTo(...) 호출합니다.

내비게이션을 하고 싶습니다. 링크가 아니라 드롭다운 선택(예:)에서. 코드에서 어떻게 할 수 있습니까? this.context 는 무엇입니까?

나는 보았다 Navigation 믹스 인을,하지만 난 않고이 작업을 수행 할 수 있습니다 mixins ?



후크가 있는 React Router v5.1.0

React >16.8.0 및 기능 구성 요소를 사용하는 경우 React Router >5.1.0에 새로운 useHistory

 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> ); }

반응 라우터 v4

React Router의 v4를 사용하면 구성 요소 내에서 프로그래밍 방식의 라우팅에 사용할 수 있는 세 가지 접근 방식이 있습니다.

  1. withRouter 고차 컴포넌트를 사용하십시오.
  2. 구성을 사용하고 <Route>
  3. context 사용합니다.

React Router는 대부분 history 라이브러리를 둘러싼 래퍼입니다. history 는 브라우저 및 해시 기록과 함께 window.history 와의 상호 작용을 처리합니다. 또한 전역 기록이 없는 환경에 유용한 메모리 기록을 제공합니다. 이는 모바일 앱 개발( react-native ) 및 Node.js로 단위 테스트에 특히 유용합니다.

history 인스턴스에는 탐색을 위한 두 가지 방법이 있습니다. pushreplace . 방문 위치의 배열로 history 을 생각한다면 push 는 배열에 새 위치를 추가하고 replace 는 배열의 현재 위치를 새 위치로 바꿉니다. 일반적으로 탐색할 때 push 방법을 사용하려고 합니다.

이전 버전의 React Router에서는 고유한 history 인스턴스를 만들어야 했지만 v4에서는 <BrowserRouter> , <HashRouter><MemoryRouter> 구성 요소가 브라우저, 해시 및 메모리 인스턴스를 생성합니다. router 객체 아래의 컨텍스트를 통해 라우터와 연결된 history 인스턴스의 속성과 메서드를 사용할 수 있도록 합니다.

1. withRouter 고차 컴포넌트 사용

withRouter 고차 구성 요소는 구성 요소의 소품으로 history context 를 처리하지 않고도 pushreplace 메서드에 액세스할 수 있습니다.

 import { withRouter } from 'react-router-dom' // this also works with react-router-native const Button = withRouter(({ history }) => ( <button type='button' onClick={() => { history.push('/new-location') }} > Click Me! </button> ))

2. 합성을 사용하여 <Route>

<Route> 구성 요소는 위치 일치만을 위한 것이 아닙니다. 경로가 없는 경로를 렌더링할 수 있으며 항상 현재 위치와 일치합니다 . <Route> withRouter 와 동일한 props를 전달 history prop을 통해 history 메서드에 액세스할 수 있습니다.

 import { Route } from 'react-router-dom' const Button = () => ( <Route render={({ history}) => ( <button type='button' onClick={() => { history.push('/new-location') }} > Click Me! </button> )} /> )

3. 컨텍스트 사용*

그러나 당신은 아마 해서는 안됩니다

마지막 옵션은 React의 컨텍스트 모델로 작업하는 것이 편안하다고 느끼는 경우에만 사용해야 하는 옵션입니다(React의 Context API는 v16부터 안정적입니다).

 const Button = (props, context) => ( <button type='button' onClick={() => { // context.history.push === history.push context.history.push('/new-location') }} > Click Me! </button> ) // you need to specify the context type so that it // is available within the component Button.contextTypes = { history: React.PropTypes.shape({ push: React.PropTypes.func.isRequired }) }

1과 2는 구현하기 가장 간단한 선택이므로 대부분의 사용 사례에서 가장 좋은 선택입니다.


Paul S

React-Router 5.1.0+ 답변(후크 및 React >16.8 사용)

기능 구성 요소에서 새로운 useHistory 후크를 사용하고 프로그래밍 방식으로 탐색할 수 있습니다.

 import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); // use history.push('/some/path') here };

React-Router 4.0.0+ 답변

4.0 이상에서는 히스토리를 컴포넌트의 소품으로 사용하십시오.

 class Example extends React.Component { // use `this.props.history.push('/some/path')` here };

<Route> 의해 렌더링되지 않은 경우 this.props.history가 존재하지 않습니다. YourComponent에 this.props.history를 포함 <Route path="..." component={YourComponent}/> 를 사용해야 합니다.

React-Router 3.0.0+ 답변

3.0 이상에서는 라우터를 구성 요소의 소품으로 사용합니다.

 class Example extends React.Component { // use `this.props.router.push('/some/path')` here };

React-Router 2.4.0+ 답변

2.4 이상에서는 구성 요소의 소품으로 라우터를 가져오기 위해 고차 구성 요소를 사용합니다.

 import { withRouter } from 'react-router'; class Example extends React.Component { // use `this.props.router.push('/some/path')` here }; // Export the decorated class var DecoratedExample = withRouter(Example); // PropTypes Example.propTypes = { router: React.PropTypes.shape({ push: React.PropTypes.func.isRequired }).isRequired };

React-Router 2.0.0+ 답변

이 버전은 1.x와 이전 버전과 호환되므로 업그레이드 가이드가 필요하지 않습니다. 예제를 살펴보는 것만으로도 충분합니다.

즉, 새 패턴으로 전환하려는 경우 라우터 내부에 다음을 사용하여 액세스할 수 있는 browserHistory 모듈이 있습니다.

import { browserHistory } from 'react-router'

이제 브라우저 기록에 액세스할 수 있으므로 푸시, 바꾸기 등과 같은 작업을 수행할 수 있습니다. 예:

browserHistory.push('/some/path')

추가 자료: 역사탐색


React-Router 1.xx 답변

나는 세부 사항을 업그레이드하지 않을 것입니다. 업그레이드 가이드 에서 이에 대해 읽을 수 있습니다.

여기서 질문에 대한 주요 변경 사항은 Navigation mixin에서 History로의 변경 사항입니다. 이제 브라우저 historyAPI를 사용하여 경로를 변경하므로 이제부터 pushState()

다음은 Mixin을 사용한 예입니다.

 var Example = React.createClass({ mixins: [ History ], navigateToHelpPage () { this.history.pushState(null, `/help`); } })

Historyrackt/history 프로젝트에서 가져온 것입니다. React-Router 자체가 아닙니다.

어떤 이유로 Mixin을 사용하지 않으려면(ES6 클래스 때문일 수 있음) this.props.history 에서 라우터에서 가져온 기록에 액세스할 수 있습니다. 라우터에서 렌더링한 구성 요소에 대해서만 액세스할 수 있습니다. 따라서 자식 구성 요소에서 사용하려면 props 를 통해 속성으로 전달해야 합니다.

1.0.x 문서 에서 새 릴리스에 대한 자세한 내용을 읽을 수 있습니다.

다음은 구성 요소 외부 탐색에 대한 도움말 페이지입니다.

history = createHistory() 잡고 이에 대해 replaceState 를 호출하는 것이 좋습니다.

React-Router 0.13.x 답변

나는 같은 문제에 빠졌고 react-router와 함께 제공되는 Navigation mixin으로 만 솔루션을 찾을 수있었습니다.

내가 한 방법은 다음과 같습니다.

 import React from 'react'; import {Navigation} from 'react-router'; let Authentication = React.createClass({ mixins: [Navigation], handleClick(e) { e.preventDefault(); this.transitionTo('/'); }, render(){ return (<div onClick={this.handleClick}>Click me!</div>); } });

.context 에 액세스할 필요 없이 transitionTo() 를 호출할 수 있었습니다.

class 사용해 볼 수 있습니다.

 import React from 'react'; export default class Authentication extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { e.preventDefault(); this.context.router.transitionTo('/'); } render(){ return (<div onClick={this.handleClick}>Click me!</div>); } } Authentication.contextTypes = { router: React.PropTypes.func.isRequired };

React-Router-Redux

참고: Redux를 사용하는 경우 React-Redux 와 다소 동일한 접근 방식을 사용하여 ReactRouter에 대한 redux 바인딩을 제공하는 React-Router-Redux 라는 다른 프로젝트가 있습니다.

React-Router-Redux에는 내부 작업 생성자로부터 간단한 탐색을 허용하는 몇 가지 방법이 있습니다. 이는 React Native에 기존 아키텍처가 있고 최소한의 상용구 오버헤드로 React Web에서 동일한 패턴을 활용하려는 사람들에게 특히 유용할 수 있습니다.

다음 방법을 살펴보십시오.

  • push(location)
  • replace(location)
  • go(number)
  • goBack()
  • goForward()

다음은 Redux-Thunk 를 사용한 사용 예입니다.

./actioncreators.js

 import { goBack } from 'react-router-redux' export const onBackPress = () => (dispatch) => dispatch(goBack())

./viewcomponent.js

 <button disabled={submitting} className="cancel_button" onClick={(e) => { e.preventDefault() this.props.onBackPress() }} > CANCEL </button>

Felipe Skinner

반응 라우터 v2

가장 최근 릴리스( v2.0.0-rc5 )의 경우 권장되는 탐색 방법은 기록 싱글톤에 직접 푸시하는 것입니다. 구성 요소 외부 탐색 문서 에서 작동 중인 것을 볼 수 있습니다.

관련 발췌문:

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

최신 react-router API를 사용하는 경우 구성 요소 내부에 있을 때 this.props history 을 사용해야 합니다.

 this.props.history.push('/some/path');

pushState 를 제공하지만 기록된 경고에 따라 더 이상 사용되지 않습니다.

react-router-redux 를 사용하는 경우 다음과 같이 push

 import { push } from 'react-router-redux'; this.props.dispatch(push('/some/path'));

그러나 이것은 URL을 변경하는 데만 사용할 수 있으며 실제로 페이지를 탐색하는 데는 사용할 수 없습니다.


Bobby

ES6 react-router v2.0.0 으로 이 작업을 수행하는 방법은 다음과 같습니다. react-router 가 믹스인에서 멀어졌습니다.

 import React from 'react'; export default class MyComponent extends React.Component { navigateToPage = () => { this.context.router.push('/my-route') }; render() { return ( <button onClick={this.navigateToPage}>Go!</button> ); } } MyComponent.contextTypes = { router: React.PropTypes.object.isRequired }

Alex Miller

React-Router 4.x 답변

결국, 나는 외부 구성 요소도 운반할 수 있는 단일 히스토리 개체를 갖고 싶습니다. 요청에 따라 가져오기만 하면 되는 단일 history.js 파일을 갖고 싶습니다.

BrowserRouter 를 Router로 변경하고 history prop을 지정하기만 하면 됩니다. 원하는 대로 조작할 수 있는 고유한 기록 개체가 있다는 점을 제외하고는 아무 것도 변경하지 않습니다.

react-router 사용하는 라이브러리인 history 를 설치해야 합니다.

사용 예, ES6 표기법:

history.js

 import createBrowserHistory from 'history/createBrowserHistory' export default createBrowserHistory()

기본 구성 요소.js

 import React, { Component } from 'react'; import history from './history'; class BasicComponent extends Component { goToIndex(e){ e.preventDefault(); history.push('/'); } render(){ return <a href="#" onClick={this.goToIndex}>Previous</a>; } }

Route 구성 요소에서 실제로 렌더링된 구성 요소에서 탐색해야 하는 경우 다음과 같이 props에서 기록에 액세스할 수도 있습니다.

기본 구성 요소.js

 import React, { Component } from 'react'; class BasicComponent extends Component { navigate(e){ e.preventDefault(); this.props.history.push('/url'); } render(){ return <a href="#" onClick={this.navigate}>Previous</a>; } }

Eric Martin

서버 측을 제어하지 않고 이 때문에 해시 라우터 v2를 사용하는 사람의 경우:

기록 을 별도의 파일(예: app_history.js ES6)에 저장합니다.

 import { useRouterHistory } from 'react-router' import { createHashHistory } from 'history' const appHistory = useRouterHistory(createHashHistory)({ queryKey: false }); export default appHistory;

그리고 어디서나 사용하세요!

react-router(app.js ES6)의 진입점:

 import React from 'react' import { render } from 'react-dom' import { Router, Route, Redirect } from 'react-router' import appHistory from './app_history' ... const render(( <Router history={appHistory}> ... </Router> ), document.querySelector('[data-role="app"]'));

모든 구성요소(ES6) 내부 탐색:

 import appHistory from '../app_history' ... ajaxLogin('/login', (err, data) => { if (err) { console.error(err); // login failed } else { // logged in appHistory.replace('/dashboard'); // or .push() if you don't need .replace() } })

Alexey Volodko

반응 라우터 v6

나는 한동안 React를 건드리지 않았지만 Shimrit Snapir의 아래 코멘트 에 감사하고 강조하고 싶습니다.

on React-Router 6.0 <Redirect /> changed to <Navigate />

반응 라우터 V4

tl:dr;

 if (navigate) { return <Redirect to="/" push={true} /> }

간단하고 선언적인 대답은 setState() 와 함께 <Redirect to={URL} push={boolean} />

push: boolean - true인 경우 리디렉션은 현재 항목을 대체하는 대신 기록에 새 항목을 푸시합니다.


 import { Redirect } from 'react-router' class FooBar extends React.Component { state = { navigate: false } render() { const { navigate } = this.state // Here is the important part if (navigate) { return <Redirect to="/" push={true} /> } // ^^^^^^^^^^^^^^^^^^^^^^^ return ( <div> <button onClick={() => this.setState({ navigate: true })}> Home </button> </div> ) } }

전체 예가 여기에 있습니다 . 여기에서 더 읽어보세요.

추신. 이 예제에서는 ES7+ 속성 이니셜라이저 를 사용하여 상태를 초기화합니다. 관심있으시면 여기도 보세요.


Lyubomir

경고: 이 답변은 1.0 이전의 ReactRouter 버전만 다룹니다.

나중에 1.0.0-rc1 사용 사례로 이 답변을 업데이트하겠습니다!

믹스인 없이도 할 수 있습니다.

 let Authentication = React.createClass({ contextTypes: { router: React.PropTypes.func }, handleClick(e) { e.preventDefault(); this.context.router.transitionTo('/'); }, render(){ return (<div onClick={this.handleClick}>Click me!</div>); } });

컨텍스트가 있는 문제는 클래스에 contextTypes 을 정의하지 않는 한 액세스할 수 없다는 것입니다.

컨텍스트는 부모에서 자식으로 전달되는 props와 같은 객체이지만 매번 props를 다시 선언할 필요 없이 묵시적으로 전달됩니다. https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html 참조


Qiming

현재 React-Router 3.0.0 및 ES6 에서 가장 간단하고 깔끔한 방법이 있습니다.

ES6이 포함된 React-Router 3.xx:

 import { withRouter } from 'react-router'; class Example extends React.Component { // use `this.props.router.push('/some/path')` here }; // Export the decorated class export default withRouter(Example);

또는 기본 클래스가 아닌 경우 다음과 같이 내보냅니다.

 withRouter(Example); export { Example };

3.xx에서 <Link> 구성 요소 자체는 router.push 를 사용하므로 다음과 같이 <Link to= 태그를 전달할 수 있는 모든 것을 전달할 수 있습니다.

 this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'

Ben Wheeler

프로그래밍 방식으로 탐색을 수행하려면 componentprops.history새 기록 을 푸시해야 하므로 다음과 같은 작업을 수행할 수 있습니다.

 //using ES6 import React from 'react'; class App extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) } handleClick(e) { e.preventDefault() /* Look at here, you can add it here */ this.props.history.push('/redirected'); } render() { return ( <div> <button onClick={this.handleClick}> Redirect!!! </button> </div> ) } } export default App;

Alireza

ES6 + React 구성 요소의 경우 다음 솔루션이 저에게 효과적이었습니다.

나는 Felippe skinner를 따랐지만 나 같은 초보자를 돕기 위해 종단 간 솔루션을 추가했습니다.

아래는 내가 사용한 버전입니다.

"반응 라우터": "^2.7.0"

"반응": "^15.3.1"

다음은 반응 라우터를 사용하여 프로그래밍 방식 탐색을 사용한 반응 구성 요소입니다.

 import React from 'react'; class loginComp extends React.Component { constructor( context) { super(context); this.state = { uname: '', pwd: '' }; } redirectToMainPage(){ this.context.router.replace('/home'); } render(){ return <div> // skipping html code <button onClick={this.redirectToMainPage.bind(this)}>Redirect</button> </div>; } }; loginComp.contextTypes = { router: React.PropTypes.object.isRequired } module.exports = loginComp;

다음은 내 라우터의 구성입니다.

 import { Router, Route, IndexRedirect, browserHistory } from 'react-router' render(<Router history={browserHistory}> <Route path='/' component={ParentComp}> <IndexRedirect to = "/login"/> <Route path='/login' component={LoginComp}/> <Route path='/home' component={HomeComp}/> <Route path='/repair' component={RepairJobComp} /> <Route path='/service' component={ServiceJobComp} /> </Route> </Router>, document.getElementById('root'));

Softwareddy

가장 좋은 방법은 아니지만... react-router v4를 사용하면 다음 TypeScript 코드가 일부 아이디어를 제공할 수 있습니다.

아래의 렌더링된 구성 요소(예: LoginPage 에서 router 개체에 액세스할 수 있으며 router.transitionTo('/homepage') 를 호출하여 탐색합니다.

탐색 코드는 에서 가져 왔습니다 .

"react-router": "^4.0.0-2", "react": "^15.3.1",

 import Router from 'react-router/BrowserRouter'; import { History } from 'react-history/BrowserHistory'; import createHistory from 'history/createBrowserHistory'; const history = createHistory(); interface MatchWithPropsInterface { component: typeof React.Component, router: Router, history: History, exactly?: any, pattern: string } class MatchWithProps extends React.Component<MatchWithPropsInterface,any> { render() { return( <Match {...this.props} render={(matchProps) => ( React.createElement(this.props.component, this.props) )} /> ) } } ReactDOM.render( <Router> {({ router }) => ( <div> <MatchWithProps exactly pattern="/" component={LoginPage} router={router} history={history} /> <MatchWithProps pattern="/login" component={LoginPage} router={router} history={history} /> <MatchWithProps pattern="/homepage" component={HomePage} router={router} history={history} /> <Miss component={NotFoundView} /> </div> )} </Router>, document.getElementById('app') );


mcku

React-Router v4ES6에서

withRouterthis.props.history.push 사용할 수 있습니다.

 import {withRouter} from 'react-router-dom'; class Home extends Component { componentDidMount() { this.props.history.push('/redirect-to'); } } export default withRouter(Home);

Hossein

클래스 기반 구성 요소와 함께 withRouter 를 사용하려면 다음과 같이 시도하십시오. withRouter 를 사용하도록 내보내기 문을 변경하는 것을 잊지 마십시오.

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

 class YourClass extends React.Component { yourFunction = () => { doSomeAsyncAction(() => this.props.history.push('/other_location') ) } render() { return ( <div> <Form onSubmit={ this.yourFunction } /> </div> ) } } export default withRouter(YourClass);

Janos

React-Router v4가 출시되면서 이제 새로운 방법이 생겼습니다.

 import { MemoryRouter, BrowserRouter } from 'react-router'; const navigator = global && global.navigator && global.navigator.userAgent; const hasWindow = typeof window !== 'undefined'; const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1; const Router = isBrowser ? BrowserRouter : MemoryRouter; <Router location="/page-to-go-to"/>

react-lego 는 react-router를 사용/업데이트하는 방법을 보여주는 예제 앱이며 앱을 탐색하는 예제 기능 테스트가 포함되어 있습니다.


peter.mouland

José Antonio Postigo 및 Ben Wheeler 의 이전 답변을 기반으로 합니다.

참신함? TypeScript 로 작성되어야 하며 데코레이터 또는 정적 속성/필드를 사용합니다.

 import * as React from "react"; import Component = React.Component; import { withRouter } from "react-router"; export interface INavigatorProps { router?: ReactRouter.History.History; } /** * Note: goes great with mobx * @inject("something") @withRouter @observer */ @withRouter export class Navigator extends Component<INavigatorProps, {}>{ navigate: (to: string) => void; constructor(props: INavigatorProps) { super(props); let self = this; this.navigate = (to) => self.props.router.push(to); } render() { return ( <ul> <li onClick={() => this.navigate("/home")}> Home </li> <li onClick={() => this.navigate("/about")}> About </li> </ul> ) } } /** * Non decorated */ export class Navigator2 extends Component<INavigatorProps, {}> { static contextTypes = { router: React.PropTypes.object.isRequired, }; navigate: (to: string) => void; constructor(props: INavigatorProps, context: any) { super(props, context); let s = this; this.navigate = (to) => s.context.router.push(to); } render() { return ( <ul> <li onClick={() => this.navigate("/home")}> Home </li> <li onClick={() => this.navigate("/about")}> About </li> </ul> ) } }

오늘 설치된 npm과 함께.

"반응 라우터": "^3.0.0" 및
"@types/react-router": "^2.0.41"


Dan

React Router v4에서는 프로그래밍 방식으로 라우팅하는 두 가지 방법을 따릅니다.

  1. this.props.history.push("/something/something")
  2. this.props.history.replace("/something/something")

두 번째

히스토리 스택의 현재 항목을 대체합니다.

소품에서 기록을 얻으려면 다음으로 구성 요소를 래핑해야 할 수 있습니다.

라우터 포함

React 라우터 v6에서

 import { useNavigate } from "react-router-dom"; function Invoices() { let navigate = useNavigate(); return ( <div> <NewInvoiceForm onSubmit={async event => { let newInvoice = await createInvoice(event.target); navigate(`/invoices/${newInvoice.id}`); }} /> </div> ); }

React Router v6 시작하기


saiful619945

해시 또는 브라우저 기록을 사용하는 경우 다음을 수행할 수 있습니다.

 hashHistory.push('/login'); browserHistory.push('/login');

Zaman Afzal

현재 React 버전(15.3)에서는 this.props.history.push('/location'); 나를 위해 일했지만 다음 경고가 표시되었습니다.

browser.js:49 경고: [react-router] props.historycontext.history 는 더 이상 사용되지 않습니다. context.router 사용하십시오.

다음과 같이 context.router 사용하여 해결했습니다.

 import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props); this.backPressed = this.backPressed.bind(this); } backPressed() { this.context.router.push('/back-location'); } ... } MyComponent.contextTypes = { router: React.PropTypes.object.isRequired }; export default MyComponent;

José Antonio Postigo

React Router v4에서 이것을 구현하는 데 문제가 있는 사람들.

다음은 redux 작업에서 React 앱을 탐색하는 작업 솔루션입니다.

파일 history.js

 import createHistory from 'history/createBrowserHistory' export default createHistory()

파일 App.js/Route.jsx

 import { Router, Route } from 'react-router-dom' import history from './history' ... <Router history={history}> <Route path="/test" component={Test}/> </Router>

파일 *another_file.js 또는 redux 파일

 import history from './history' history.push('/test') // This should change the URL and rerender Test component

GitHub의 이 댓글 덕분입니다: ReactTraining 문제 댓글


reflexgravity

후크가 있는 React Router v6

 import {useNavigate} from 'react-router-dom'; let navigate = useNavigate(); navigate('home');

브라우저 기록을 가로질러 이동하려면

 navigate(-1); ---> Go back navigate(1); ---> Go forward navigate(-2); ---> Move two steps backward.

Vijay122

반응 라우터 V4

버전 4를 사용하는 경우 작업을 전달하기만 하면 모든 것이 제대로 작동하는 내 라이브러리( 뻔뻔한 플러그)를 사용할 수 있습니다!

 dispatch(navigateTo("/aboutUs"));

트리플러


Garry Taylor

상태 비저장 구성 요소에서useHistory 후크를 사용할 수도 있습니다. 문서의 예:

 import { useHistory } from "react-router" function HomeButton() { const history = useHistory() return ( <button type="button" onClick={() => history.push("/home")}> Go home </button> ) }

참고: 후크는 react-router@5.1.0 react@>=16.8 필요합니다.


Nickofthyme

클래스 기반 구성 요소에서 프로그래밍 방식으로 탐색합니다.

 import { Redirect } from "react-router-dom"; class MyComponent extends React.Component{ state = {rpath: null} const goTo = (path) => this.setState({rpath: path}); render(){ if(this.state.rpath){ return <Redirect to={this.state.rpath}/> } ..... ..... } }

shivampip

글을 쓰는 시점의 나에게 정답이 있었다

 this.context.router.history.push('/');

그러나 구성 요소에 PropTypes를 추가해야 합니다.

 Header.contextTypes = { router: PropTypes.object.isRequired } export default Header;

PropTypes 가져오기를 잊지 마세요.

 import PropTypes from 'prop-types';

webmaster

"react-router에 대한 최신 대안"인 React Hook Router를 대신 사용해보십시오.

 import { useRoutes, usePath, A} from "hookrouter";

선택 상자를 통한 연결에 대한 OP의 질문에 대답하려면 다음을 수행하십시오.

 navigate('/about');

업데이트된 답변

나는 React Hook Router가 좋은 스타터 키트였고 라우팅에 대해 배우는 데 도움이 되었다고 생각하지만, 그 이후로 이력 및 쿼리 매개변수 처리를 위해 React Router로 업데이트했습니다.

 import { useLocation, useHistory } from 'react-router-dom'; const Component = (props) => { const history = useHistory(); // Programmatically navigate history.push(newUrlString); }

location.history로 이동하려는 위치를 푸시합니다.


StefanBob

최선의 솔루션은 아니지만 작업을 완료합니다.

 import { Link } from 'react-router-dom'; // Create functional component Post export default Post = () => ( <div className="component post"> <button className="button delete-post" onClick={() => { // ... delete post // then redirect, without page reload, by triggering a hidden Link document.querySelector('.trigger.go-home').click(); }}>Delete Post</button> <Link to="/" className="trigger go-home hidden"></Link> </div> );

기본적으로 하나의 작업(이 경우 삭제 후)에 연결된 논리는 리디렉션을 위한 트리거를 호출하게 됩니다. 필요할 때 편리하게 호출할 수 있도록 마크업에 DOM 노드 '트리거'를 추가하기 때문에 이것은 이상적이지 않습니다. 또한 React 구성 요소에서 원하지 않을 수 있는 DOM과 직접 상호 작용합니다.

그러나 이러한 유형의 리디렉션은 그렇게 자주 필요하지 않습니다. 따라서 구성 요소 마크업에 하나 또는 두 개의 추가 숨겨진 링크가 있는 경우, 특히 의미 있는 이름을 지정하는 경우 그다지 문제가 되지 않습니다.


neatsu

당신을 통해 REDUX와 RR4를 페어링 일 경우 반응-라우터 REDUX 에서 라우팅 액션 제작자를 사용하여, react-router-redux 아니라 옵션입니다.

 import { push, replace, ... } from 'react-router-redux' class WrappedComponent extends React.Component { handleRedirect(url, replaceState = true) { replaceState ? this.props.dispatch(replace(url)) : this.props.dispatch(push(url)) } render() { ... } } export default connect(null)(WrappedComponent)

redux thunk/saga를 사용하여 비동기 흐름을 관리하는 경우 redux 작업에서 위의 작업 생성자를 가져오고 mapDispatchToProps를 사용하여 React 구성 요소에 연결하는 것이 더 나을 수 있습니다.


Xlee

내 대답에는 프로그래밍 방식으로 경로로 리디렉션하는 세 가지 방법이 있습니다. 일부 솔루션은 이미 제시되었지만 다음 솔루션은 추가 데모 애플리케이션이 있는 기능 구성요소에만 초점을 맞춥니다.

다음 버전 사용:

반응: 16.13.1

반응돔: 16.13.1

반응 라우터: 5.2.0

반응 라우터 돔: 5.2.0

타이프스크립트: 3.7.2

구성:

따라서 먼저 솔루션은 다음과 같이 구성된 HashRouter

 <HashRouter> // ... buttons for redirect <Switch> <Route exact path="/(|home)" children={Home} /> <Route exact path="/usehistory" children={UseHistoryResult} /> <Route exact path="/withrouter" children={WithRouterResult} /> <Route exact path="/redirectpush" children={RedirectPushResult} /> <Route children={Home} /> </Switch> </HashRouter>

<HashRouter> 에 대한 문서 에서 :

URL의 해시 부분(예: window.location.hash )을 사용하여 UI를 URL과 동기화된 상태로 유지하는 <Router>

솔루션:

  1. <Redirect> 를 사용하여 useState 사용하여 푸시:

기능 구성 요소( RedirectPushAction 구성 요소)에서 useState 를 사용하여 리디렉션을 처리할 수 있습니다. 까다로운 부분은 리디렉션이 발생하면 redirect 상태를 다시 false 로 설정해야 한다는 것입니다. 0 setTimeOut 을 사용함으로써 Redirect 를 DOM에 커밋할 때까지 기다렸다가 다음 번에 그것을 사용하기 위해 버튼을 다시 가져옵니다.

아래에서 내 예를 찾으십시오.

 const [redirect, setRedirect] = useState(false); const handleRedirect = useCallback(() => { let render = null; if (redirect) { render = <Redirect to="/redirectpush" push={true} /> // In order wait until committing to the DOM // and get back the button for clicking next time setTimeout(() => setRedirect(false), 0); } return render; }, [redirect]); return <> {handleRedirect()} <button onClick={() => setRedirect(true)}> Redirect push </button> </>

<Redirect> 문서에서:

<Redirect> 렌더링하면 새 위치로 이동합니다. 새 위치는 서버 측 리디렉션(HTTP 3xx)과 같이 기록 스택의 현재 위치를 재정의합니다.

  1. useHistory 후크 사용:

내 솔루션에는 다음을 나타내는 UseHistoryAction 이라는 구성 요소가 있습니다.

 let history = useHistory(); return <button onClick={() => { history.push('/usehistory') }}> useHistory redirect </button>

useHistory 후크는 경로를 프로그래밍 방식으로 탐색하거나 변경하는 데 도움이 되는 기록 개체에 대한 액세스를 제공합니다.

  1. withRouter 사용하여 props history 을 가져옵니다.

WithRouterAction 이라는 구성 요소를 하나 생성하면 아래와 같이 표시됩니다.

 const WithRouterAction = (props:any) => { const { history } = props; return <button onClick={() => { history.push('/withrouter') }}> withRouter redirect </button> } export default withRouter(WithRouterAction);

withRouter 문서에서 읽기:

withRouter 고차 구성 요소 history 개체의 속성과 가장 가까운 <Route> 의 일치 항목에 액세스할 수 있습니다. withRouter 는 렌더링될 때마다 업데이트된 match , locationhistory props를 래핑된 구성 요소에 전달합니다.

데모:

더 나은 표현을 위해 이 예제를 사용하여 GitHub 리포지토리를 구축했습니다. 아래에서 찾으십시오.

React Router 프로그래밍 방식으로 예제 리디렉션


norbitrial

이것은 나를 위해 일했으며 특별한 수입품이 필요하지 않았습니다.

 <input type="button" name="back" id="back" class="btn btn-primary" value="Back" onClick={() => { this.props.history.goBack() }} />

JJ_Coder4Hire

출처 : http:www.stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router

반응형