내가 사용하고 마지막 버전 반응 라우터 모듈 이름에 반응 라우터 dom,는 기본을 개발할 때 사용하는 웹 애플리케이션용으로 반응한다. 내가하는 방법을 알고 싶다면 확인 후 리디렉션 게시물을 요청합니다. 내가 이 코드가 있지만,요청 후,아무 일도 일어나지 않습니다. 가 웹상에서 하지만,모든 데이터가 이전 버전의 반응 라우터,및 마지막 업데이트합니다.
코드:
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
async processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
errors: {}
});
<Redirect to="/"/> // Here, nothings happens
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
<SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
당신이 사용하는setState
속성을 설정하는 것입니다 렌더링<리디렉션>
내부render()
방법입니다.
E.g.
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
axios.post(/**/)
.then(() => this.setState({ redirect: true }));
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/somewhere'/>;
}
return <RenderYourForm/>;
}
할 수도 있습니다 예를 참조하십시오 공식 문서:https://reacttraining.com/react-router/web/example/auth-workflow
는 말했다,나는 당신을 넣어 API 를 통하거나 서비스 또는 무언가이다. 그럼 당신이 사용할 수 있습니의기록
체 경로를 사용하여 프로그래밍 방식으로. 이통합으로 돌아오작동합니다.
그러나 나는 당신이 당신의 이유로 그것을 하는 이 방법입니다.
여기에 작은 예로 응답하는 제목으로 모든 언급된 예는 복잡한에서 내 의견 뿐 아니라 공식니다.
당신이하는 방법을 알고 있어야 transpile es2015 뿐만 아니라 서버가 처리할 수 있 리디렉션합니다. 여기에 조각을 위해 표현한다. 더 많은 정보와 관련된 이 발견될 수 있는여기서.
게 이 아래는 모든 다른 노선이 있습니다.
const app = express();
app.use(express.static('distApp'));
/**
* Enable routing with React.
*/
app.get('*', (req, res) => {
res.sendFile(path.resolve('distApp', 'index.html'));
});
이것입니다.jsx 파일입니다. 알 수 있는 방법을 가장 긴 경로를 먼저 얻's 이 더 일반적입니다. 에 대한 가장 일반적인 경로를 사용하여 정확한 특성입니다.
// Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
// Absolute imports
import YourReactComp from './YourReactComp.jsx';
const root = document.getElementById('root');
const MainPage= () => (
<div>Main Page</div>
);
const EditPage= () => (
<div>Edit Page</div>
);
const NoMatch = () => (
<p>No Match</p>
);
const RoutedApp = () => (
<BrowserRouter >
<Switch>
<Route path="/items/:id" component={EditPage} />
<Route exact path="/items" component={MainPage} />
<Route path="/yourReactComp" component={YourReactComp} />
<Route exact path="/" render={() => (<Redirect to="/items" />)} />
<Route path="*" component={NoMatch} />
</Switch>
</BrowserRouter>
);
ReactDOM.render(<RoutedApp />, root);
도 같은 것이다.
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
callbackResponse: null,
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
callbackResponse: {response.data},
});
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
const renderMe = ()=>{
return(
this.state.callbackResponse
? <SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
: <Redirect to="/"/>
)}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
{renderMe()}
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
반응 라우터 v5 지금은 단순히를 사용하여 리디렉션 역사입니다.push()감사를useHistory()훅:
``jsx 가져오기{useHistory}에서"반응 라우터"
기능 HomeButton(){ 자 역사=useHistory()
기능 handleClick(){ 역사입니다.push("/홈") }
return(
또는,당신은사용할 수 있습니다 withRouter
. 당신은에 액세스 할 수 있습니다역사
object's 의 속성에 가장 가까운<루>
's경기
를 통해withRouter
순위가 높은 구성 요소입니다.withRouter
통과할 것입 업데이트경기
,위치
및기록
소품을 감소할 때마다 그것은 렌더링합니다.
import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return <div>You are now at {location.pathname}</div>
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
또:
import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
"반응":"^16.3.2", "반응 dom":"^16.3.2", "반응 라우터 dom":"^4.2.2"
에 대한 다른 페이지로 이동하여(페이지에 대한 내 경우),제가 설치품 유형
입니다. 그때 나는 수입에 해당하는 구성 요소입니다.고 내가 사용하는이다.context.라우터입니다.역사입니다.push('/에 대한')
.고 그것은 탐색.
나의 코드입니다,
import React, { Component } from 'react';
import '../assets/mystyle.css';
import { Redirect } from 'react-router';
import PropTypes from 'prop-types';
export default class Header extends Component {
viewAbout() {
this.context.router.history.push('/about')
}
render() {
return (
<header className="App-header">
<div className="myapp_menu">
<input type="button" value="Home" />
<input type="button" value="Services" />
<input type="button" value="Contact" />
<input type="button" value="About" onClick={() => { this.viewAbout() }} />
</div>
</header>
)
}
}
Header.contextTypes = {
router: PropTypes.object
};
로 이동하는 다른 구성 요소를 사용할 수 있습이다.props.역사입니다.push('/주');
import React, { Component, Fragment } from 'react'
class Example extends Component {
redirect() {
this.props.history.push('/main')
}
render() {
return (
<Fragment>
{this.redirect()}
</Fragment>
);
}
}
export default Example
를 작성할 수 있습니다 hoc 이 목적을 위해 작성 방법 전화 리디렉션 코드는 다음과 같습니다:
import React, {useState} from 'react';
import {Redirect} from "react-router-dom";
const RedirectHoc = (WrappedComponent) => () => {
const [routName, setRoutName] = useState("");
const redirect = (to) => {
setRoutName(to);
};
if (routName) {
return <Redirect to={"/" + routName}/>
}
return (
<>
<WrappedComponent redirect={redirect}/>
</>
);
};
export default RedirectHoc;
사용할 수 있습니다,또는 반응의 조건부 렌더링을 수행합니다.
`` 가져오기{Redirect}에서"반응 라우터"; 가져오기 반응,{구성 요소}에서'반응';
클래스 UserSignup 확장 구성 요소{ 생성자(소품){ super(소품); 다.state={ redirect:false } } render(){ <반응합니다.단편> {this.상태입니다.redirect&&<Redirect="/로그"/>}//로 리디렉션됩니다 로그로 } </React.단편> } ``