react-router를 사용하여 다른 경로로 리디렉션하는 방법은 무엇입니까?
다른보기로 리디렉션하기 위해 react-router ( 버전 ^ 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'에 사용을 보내는 것뿐입니다.
어떡해 ?
콘솔 오류 :
포착되지 않은 ReferenceError : 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>
);
간단한 대답을 위해 대신 Link
에서 구성 요소를 사용할 수 있습니다 . JS에서 경로를 변경하는 방법이 있지만 여기서는 필요하지 않은 것 같습니다.react-router
button
<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
정의에 언급 된 하위 구성 요소 아래에있는 경우 추가로 전달해야 할 수 있습니다.
1) react-router> V4 withRouter
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 (
<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>
);
}
};
}
export default withRouter(YourComponent);
2) 반응 라우터 <V4
react-router를 사용하여이 기능을 수행 할 수 있습니다 BrowserHistory
. 아래 코드 :
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/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>
);
}
};
}
3) redux 사용 connected-react-router
당신이 REDUX와 구성 요소를 연결 한 및 구성한 경우 연결-반응 라우터 당신이해야 할 모든 것입니다 this.props.history.push("/new/url");
즉, 당신은 필요가 없습니다 withRouter
주입 HOC를 history
구성 요소 소품에.
// 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';
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 (
<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>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
How to do a redirect to another route with react-router?
For example, when a user clicks a link <Link to="/" />Click to route</Link>
react-router will look for /
and you can use Redirect to
and send the user somewhere else like the login route.
From the docs for ReactRouterTraining:
Rendering a
<Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
to: string, The URL to redirect to.
<Redirect to="/somewhere/else"/>
to: object, A location to redirect to.
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/>
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
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');
}
}
The simplest solution is:
import { Redirect } from 'react-router';
<Redirect to='/componentURL' />
참고URL : https://stackoverflow.com/questions/34735580/how-to-do-a-redirect-to-another-route-with-react-router
'developer tip' 카테고리의 다른 글
++ 연산자에 관한 C와 C ++의 차이점 (0) | 2020.11.02 |
---|---|
컬렉션의 구문을 설명하십시오. (0) | 2020.11.02 |
GraphViz에 비해 너무 큰 무 방향 그래프 시각화? (0) | 2020.11.02 |
CSS-ID 내에서 클래스를 선택하는 구문 (0) | 2020.11.02 |
Visual Studio를 VB.NET 대신 C # 프로젝트로 기본 설정하는 방법은 무엇입니까? (0) | 2020.11.02 |