리액트 라우터를 사용하여 다른 루트로 리다이렉트하려면 어떻게 해야 하나요?
리액트 라우터(버전^1.0.3)를 사용하여 다른 뷰로 리다이렉트하여 A SIMPLE을 실행하려고 합니다.
import React from 'react';
import {Router, Route, Link, RouteHandler} from 'react-router';
class HomeSection extends React.Component {
static contextTypes = {
router: PropTypes.func.isRequired
};
constructor(props, context) {
super(props, context);
}
handleClick = () => {
console.log('HERE!', this.contextTypes);
// this.context.location.transitionTo('login');
};
render() {
return (
<Grid>
<Row className="text-center">
<Col md={12} xs={12}>
<div className="input-group">
<span className="input-group-btn">
<button onClick={this.handleClick} type="button">
</button>
</span>
</div>
</Col>
</Row>
</Grid>
);
}
};
HomeSection.contextTypes = {
location() {
React.PropTypes.func.isRequired
}
}
export default HomeSection;
사용자를 '/login'으로 전송하기만 하면 됩니다.
내가 뭘 할 수 있을까?
콘솔 오류:
수집되지 않은 참조 오류: PropTypes가 정의되지 않았습니다.
내 경로와 함께 파일링
// LIBRARY
/*eslint-disable no-unused-vars*/
import React from 'react';
/*eslint-enable no-unused-vars*/
import {Route, IndexRoute} from 'react-router';
// COMPONENT
import Application from './components/App/App';
import Contact from './components/ContactSection/Contact';
import HomeSection from './components/HomeSection/HomeSection';
import NotFoundSection from './components/NotFoundSection/NotFoundSection';
import TodoSection from './components/TodoSection/TodoSection';
import LoginForm from './components/LoginForm/LoginForm';
import SignupForm from './components/SignupForm/SignupForm';
export default (
<Route component={Application} path='/'>
<IndexRoute component={HomeSection} />
<Route component={HomeSection} path='home' />
<Route component={TodoSection} path='todo' />
<Route component={Contact} path='contact' />
<Route component={LoginForm} path='login' />
<Route component={SignupForm} path='signup' />
<Route component={NotFoundSection} path='*' />
</Route>
);
1) 리액트 라우터> V6useNavigate
후크:
가지고 계신 경우React >= 16.8
및 기능 컴포넌트를 사용할 수 있습니다.useNavigate
리액트 리액트 리액트 리액트 리액트 훅
import React from 'react';
import { useNavigate } from "react-router-dom";
const YourComponent = () => {
const navigate = useNavigate();
const handleClick = () => {
navigate("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
2) 리액트 라우터> V5useHistory
후크:
가지고 계신 경우react-router v5
및 기능 컴포넌트를 사용할 수 있습니다.useHistory
리액트 리액트 리액트 리액트 리액트 훅
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
3) 리액트 라우터> V4withRouter
HOC:
댓글에서 @ambar가 언급했듯이 React-router는 V4 이후 코드 베이스를 변경했습니다.다음은 WithRouter에 대한 문서입니다.
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
4) 리액트 라우터 < V4:browserHistory
리액트 라우터를 사용하여 이 기능을 구현할 수 있습니다.BrowserHistory
. 아래 코드:
import React, { Component } from 'react';
import { browserHistory } from 'react-router-dom';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
5) 삭감connected-react-router
컴포넌트를 redx로 연결하고 connected-react-router를 설정한 경우 필요한 작업은 다음과 같습니다.this.props.history.push("/new/url");
즉, 필요 없습니다.withRouter
주입하는 HOChistory
컴포넌트 소품까지.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
간단한 답변은 다음과 같이 사용할 수 있습니다.Link
에서 구성 요소react-router
대신button
JS에서는 루트를 변경하는 방법이 있습니다만, 여기서 변경할 필요는 없는 것 같습니다.
<span className="input-group-btn">
<Link to="/login">Click to login</Link>
</span>
1.0.x에서 프로그래밍 방식으로 실행하려면 clickHandler 함수 내에서 다음과 같이 수행합니다.
this.history.pushState(null, 'login');
업그레이드 문서에서 가져왔습니다.
그랬어야 했는데this.history
루트 핸들러 컴포넌트에 배치하다react-router
에 기재되어 있는 하위 컴포넌트인 경우routes
정의, 당신은 그것을 더 넘겨줄 필요가 있을 수 있습니다.
리액트 라우터를 사용하여 다른 루트로 리다이렉트하려면 어떻게 해야 하나요?
예를 들어 사용자가 링크를 누른 경우<Link to="/" />Click to route</Link>
리액트 리액트 리액트 리액트 리액트 리액트는/
를 사용할 수 있습니다.Redirect to
로그인 루트등의 다른 장소에 유저를 송신합니다.
렌더링
<Redirect>
새 위치로 이동합니다.서버측의 리다이렉트(HTTP 3xx)와 같이, 새로운 로케이션은 이력 스택내의 현재의 로케이션을 덮어씁니다.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
to: string, 리다이렉트처의 URL.
<Redirect to="/somewhere/else"/>
대상: 오브젝트, 리다이렉트할 위치.
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/>
웹을 위한 가장 쉬운 솔루션!
최신판 2020
확인 대상:
"react-router-dom": "^5.1.2"
"react": "^16.10.2"
갈고리를 사용해!
import React from 'react';
import { useHistory } from "react-router-dom";
export function HomeSection() {
const history = useHistory();
const goLogin = () => history.push('login');
return (
<Grid>
<Row className="text-center">
<Col md={12} xs={12}>
<div className="input-group">
<span className="input-group-btn">
<button onClick={goLogin} type="button" />
</span>
</div>
</Col>
</Row>
</Grid>
);
}
오래된 질문이지만 2021년 이후 React Router V6에서 useHistory가 react-router-dom에서 내보내지지 않으므로 대신 useNavigate를 Import해야 합니다.샘플 코드는 다음과 같습니다.
import { useNavigate } from "react-router-dom"
반응 클래스 또는 기능 컴포넌트 내부:
const navigate = useNavigate()
navigate("/404")
react-router v2.8.1(아마 다른 2.x.x 버전도 테스트하지 않았을 가능성이 있습니다)에서는 이 실장을 사용하여 라우터의 리다이렉트를 실행할 수 있습니다.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
가장 간단한 해결책은 다음과 같습니다.
import { Redirect } from 'react-router';
<Redirect to='/componentURL' />
라우팅 라이브러리를 사용하지 않는 가장 간단한 방법
window.location.replace("/login")
react-module-dom 버전 업데이트 > = 6
useHistory
has has has has has has has has has has has has has has has 로 되었습니다.useNavigate
.
하시면 됩니다.useNavigate
음음음같 뭇매하다
import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/login');
리액트 라우터 솔루션
이 솔루션이 필요한 이유:컴포넌트의 로딩이 빨라지고 루트가 향상됩니다(예: www.website.com/**signup**) 및 컴포넌트에 링크된 컴포넌트를 한 곳에서 쉽게 관리할 수 있습니다).
방법: 예를 들어 www.website.com/**home**에서 index.display 내의 컴포넌트에 대한 경로를 설정합니다.그런 다음 기본적으로 다른 컴포넌트의 하이퍼링크를 사용하여 해당 루트로 이동합니다.
순서 1: 리액트 라우터 돔을 설치합니다.
npm install react-router-dom
스텝 2: ./src에서 Start 컴포넌트와 SignUp 컴포넌트를 만듭니다.
Start.jsx
import React from 'react';
import { Link } from 'react-router-dom';
class Start extends React.Component {
constructor(props) {
super(props);
}
render () {
return (
<div>
<h1>Hello World!</h1>
<Link to='signUp'>Sign Up</Link>
</div>
);
}
};
export default Start
SignUp.jsx
import React from "react";
class SignUp extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Sign Up</h1>
<p>Sign up page</p>
</div>
);
}
}
export default SignUp;
3단계: 이 코드를 사용하여 index.js 및 App.js를 업데이트합니다.
index.displaces를 표시합니다.
//Imports
import React from 'react';
import ReactDOM from 'react-dom/client';
import { createBrowserRouter, RouterProvider} from 'react-router-dom';
import SignUp from './SignUp';
import Start from './Start';
/*This is where you create the routes - path is the
route and element is the component that will be found there. */
const router = createBrowserRouter([
{
path: '/',
element: <Start />
},
{
path: 'signUp',
element: <SignUp />
}
]);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<RouterProvider router = { router } />
</React.StrictMode>
);
App.js
import React from "react";
import Start from "./Start";
function App() {
return (
<div>
<Start />
</div>
);
}
export default App;
완료. 더 이상 기능 구성요소는 클라이언트 측 라우팅 및 쉬운 경로 관리만 탐색합니다.
언급URL : https://stackoverflow.com/questions/34735580/how-to-do-a-redirect-to-another-route-with-react-router
'programing' 카테고리의 다른 글
Google의 폴리머는 다른 프런트 엔드 프레임워크를 보완하거나 보완하기 위한 완전한 기능을 갖춘 프런트 엔드 프레임워크입니까? (0) | 2023.04.04 |
---|---|
React.useState는 소품에서 상태를 새로고침하지 않습니다. (0) | 2023.04.04 |
리액트 컴포넌트의 DOM을 변환하는 JQuery 플러그인을 사용하고 있습니까? (0) | 2023.04.04 |
JsonRequestBehavior를 AllowGet으로 설정할 때 어떤 '중요한 정보'가 공개될 수 있습니까? (0) | 2023.04.04 |
Oracle의 기본 날짜 형식은 YYY-MM-DD입니다. 이유는 무엇입니까? (0) | 2023.04.04 |