codememo

리액트 리액트 리액트 리액트 리액트 리액트 리액트 리액트 리

tipmemo 2023. 2. 16. 21:44
반응형

리액트 리액트 리액트 리액트 리액트 리액트 리액트 리액트 리

어떻게 하면 이전 페이지로 돌아갈 수 있는지 알아보고 있습니다.하고 .[react-router-v4][1]

첫 번째 랜딩 페이지에서 설정한 코드는 다음과 같습니다.

<Router>
  <div>
    <Link to="/"><div className="routerStyle"><Glyphicon glyph="home" /></div></Link>
    <Route exact path="/" component={Page1}/>
    <Route path="/Page2" component={Page2}/>
    <Route path="/Page3" component={Page3}/>
  </div>
</Router>

다음 페이지로 전송하려면 다음 작업을 수행합니다.

this.props.history.push('/Page2');

그런데 어떻게 하면 이전 페이지로 돌아갈 수 있나요? 몇 잘 되지 1. 래래와같: tried tried tried tried tried tried tried tried tried tried tried tried tried tried 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 .1.this.props.history.goBack();

에러를 표시합니다.

TypeError: null은 개체가 아닙니다('this.props' 평가).

  1. this.context.router.goBack();

에러를 표시합니다.

TypeError: null은 개체가 아닙니다('this.context' 평가 중).

  1. this.props.history.push('/');

에러를 표시합니다.

TypeError: null은 개체가 아닙니다('this.props' 평가).

님의 >Page1래래: :

import React, {Component} from 'react';
import {Button} from 'react-bootstrap';

class Page1 extends Component {
  constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
  }


  handleNext() {
    this.props.history.push('/page2');
  }

  handleBack() {
    this.props.history.push('/');
  }


  /*
   * Main render method of this class
   */
  render() {
    return (
      <div>
        {/* some component code */}


        <div className="navigationButtonsLeft">
          <Button onClick={this.handleBack} bsStyle="success">&lt; Back</Button>
        </div>
        <div className="navigationButtonsRight">
          <Button onClick={this.handleNext} bsStyle="success">Next &gt;</Button>
        </div>

      </div>
    );
  }


export default Page1;

이 문제는 바인딩에 있다고 생각합니다.

constructor(props){
   super(props);
   this.goBack = this.goBack.bind(this); // i think you are missing this
}

goBack(){
    this.props.history.goBack();
}

.....

<button onClick={this.goBack}>Go Back</button>

당신이 코드를 올리기 전에 내가 추측했듯이:

constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
    this.handleBack = this.handleBack.bind(this); // you are missing this line
}

갱신:

훅이 생겼기 때문에 useHistory를 사용하면 간단하게 할 수 있습니다.

const history = useHistory()

const goBack = () => {
  history.goBack()
}

return (
  <button type="button" onClick={goBack}>
    Go back
  </button>
);

최초 투고:

this.props.history.goBack();

이것은 리액트 라우터 v4의 올바른 솔루션입니다.

하지만 한 가지 명심해야 할 점은 이 프로포즈를 확실히 해야 한다는 것입니다.역사는 존재합니다.

, 이 를 '아, 아, 아, 아, 아, 아, 아, 하다'라고 합니다.this.props.history.goBack();< /> < Route / >에 의해

컴포넌트 트리의 깊숙한 컴포넌트에서 이 함수를 호출하면 동작하지 않습니다.

편집:

컴포넌트 트리의 안쪽 컴포넌트(< Route >로 둘러싸이지 않음)에 이력 오브젝트를 포함시키는 경우는, 다음과 같이 실시할 수 있습니다.

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

class Demo extends Component {
    ...
    // Inside this you can use this.props.history.goBack();
}

export default withRouter(Demo);

리액트 라우터 v4 및 돔 트리 내의 기능 컴포넌트와 함께 사용합니다.

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

const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;

export default withRouter(GoBack);

각 답변에는 토탈 솔루션의 일부가 포함되어 있습니다.다음은 Route가 사용된 곳보다 더 깊이 있는 컴포넌트 내부에서 동작하도록 하기 위해 사용한 완전한 솔루션입니다.

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

^ 이 두 번째 줄은 함수를 가져오고 페이지 하단에 구성요소를 내보내려면 필요합니다.

render() {
  return (
  ...
    <div onClick={() => this.props.history.goBack()}>GO BACK</div>
  )
}

^ 화살표 기능 vs onClick={this.props} 필요.history.goBack()}

export default withRouter(MyPage)

^ 컴포넌트 이름을 'withRouter'()로 감습니다.

문제를할 수 을 다음에 이 문제는 할 수 가 될 가능성이 있습니다.이 방법에서는, 생각할 수 있는 리스크도 무효가 됩니다.this keyword를 사용합니다 이치노

import { withRouter } from "react-router-dom";을 하다component 더 나은 ★★★★★★★★★ ★★★★App.jswithRouter() HOC 하면 '''가 된다'history '앱 전체할 수 .history available for that specific 컴포넌트를 선택합니다.

다음과 같은 것이 있습니다.

  1. export default withRouter(App);

  2. 에서 Redux » export default withRouter( connect(mapStateToProps, { <!-- your action creators -->})(App), ); '사용할 수 있다'는 도 할 수 합니다.history액션 크리에이터에게 이런 식으로.

당신의 안에서component다음을 수행합니다.

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

const history = useHistory(); // do this inside the component

goBack = () => history.goBack();

<btn btn-sm btn-primary onclick={goBack}>Go Back</btn>

export default DemoComponent;

갓차useHistory최신 v5.1에서만 내보냅니다.react-router-dom패키지는 반드시 갱신해 주세요.하지만, 당신은 걱정할 필요가 없습니다.this keyword.

또한 앱 전체에서 사용할 수 있는 재사용 가능한 구성 요소로 만들 수도 있습니다.


function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}```
Cheers.

사용할 코드를 제공할 수 있습니까?this.props.history.push('/Page2');?

goBack() 메서드를 사용해 보셨습니까?

this.props.history.goBack();

여기 https://reacttraining.com/react-router/web/api/history에 게재되어 있습니다.

https://reacttraining.com/react-router/web/example/modal-gallery의 라이브 예시를 참조해 주세요.

리액트 훅을 사용하는 경우 다음 작업만 수행합니다.

import { useHistory } from "react-router-dom";
const history = useHistory();
history.go(-1);

업데이트 2022 W V6

navigate(-1)

기록에서 현재 페이지를 생략하려면:

navigate(-1, { replace: true })

시험:

this.props.router.goBack()

간단하게 사용

<span onClick={() => this.props.history.goBack()}>Back</span>

이것이 도움이 되기를 바랍니다.

import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';

interface Props {
  history: History;
}

@withRouter
export default class YourComponent extends React.PureComponent<Props> {

  private onBackClick = (event: React.MouseEvent): void => {
    const { history } = this.props;
    history.goBack();
  };

...

이게 누군가를 도울 수 있을지도 몰라

사용하고 있었습니다.history.replace()리다이렉트 하려고 했을 때history.goBack()작업하고 있던 페이지보다 이전 페이지로 보내졌습니다.그래서 방법을 바꿨다.history.replace()로.history.push()역사를 살릴 수 있고, 다시 돌아갈 수 있을 것 같아요.

다른 사람이 이 문제에 부딪혔는지 확인해야 하는지 잘 모르겠습니다.하지만 저는 이 문제를 해결하기 위해 약 3시간을 보냈습니다.

버튼 클릭 한 번으로 간단한 goBack()을 구현하고 싶었습니다.App.js가 이미 라우터에 랩되어 있고 'react-router-dom'에서 {BrowserRouter as Router}을(를) Import하고 있었기 때문에 순조로운 출발이라고 생각했습니다.Router 요소에서는 이력 오브젝트를 평가할 수 있습니다.

예:

import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
  return (
    <Router>
      <Header />
      <Route path='/' component={Splash} exact />
      <Route path='/home' component={Info} exact />
      <Route path='/timer' component={Timer} exact />
      <Route path='/options' component={Options} exact />
      <Footer />
    </Router>
  );
}
export default App;

그러나 Nav(자체 구성 요소) 모듈에서 문제가 발생하여 'react-router-dom'에서 {withRouter}을(를) Import한 후 강제로 내보내야 했습니다.

export default withRouter(Nav);

예:

import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
    render() {
        return (
            <div>
                <label htmlFor='back'></label>
                <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                <label htmlFor='logOut'></label>
                <button id='logOut' ><a href='./'>Log-Out</a>            
</button>
            </div>
        );
    }
}
export default withRouter(Nav);

요약하면 라우터로부터의 상속이 거부되는 특정 시나리오에서 강제 내보내기가 필요한 React의 기존 문제로 인해 withRouter가 작성되었습니다.

사용할 수 있습니다.history.goBack()기능 컴포넌트에 포함되어 있습니다.이것처럼만.

import { useHistory } from 'react-router';
const component = () => { 
  const history = useHistory();

  return (
   <button onClick={() => history.goBack()}>Previous</button>
  )
}

언급URL : https://stackoverflow.com/questions/46681387/react-router-v4-how-to-go-back

반응형