Saya menggunakan versi terakhir bereaksi-router modul, bernama bereaksi-router-dom, yang telah menjadi default ketika mengembangkan aplikasi web dengan Bereaksi. Saya ingin tahu bagaimana untuk membuat pengalihan setelah permintaan POST. Saya telah membuat kode ini, tapi setelah permintaan, tidak ada yang terjadi. Saya review di web, tapi semua data tentang versi sebelumnya yang bereaksi router, dan tidak dengan update terakhir.
Kode:
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;
Anda harus menggunakan setState
untuk mengatur properti yang akan membuat <Mengarahkan>
di dalam render()
metode.
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/>;
}
Anda juga dapat melihat contoh dalam dokumentasi resmi: https://reacttraining.com/react-router/web/example/auth-workflow
Yang mengatakan, saya akan menyarankan anda untuk menempatkan panggilan API dalam layanan atau sesuatu. Maka anda hanya bisa menggunakan sejarah
objek untuk rute programatik. Ini adalah bagaimana integrasi dengan redux karya-karya.
Tapi saya kira anda memiliki alasan anda untuk melakukannya dengan cara ini.
Berikut ini contoh kecil sebagai respon untuk judul karena semua yang disebutkan contoh-contoh yang rumit dalam pendapat saya serta resmi.
Anda harus tahu bagaimana untuk transpile es2015 serta membuat server anda mampu menangani mengarahkan. Berikut adalah cuplikan untuk mengekspresikan. Info lebih lanjut terkait hal ini dapat ditemukan di sini.
Pastikan untuk menempatkan ini berikut semua rute lainnya.
const app = express();
app.use(express.static('distApp'));
/**
* Enable routing with React.
*/
app.get('*', (req, res) => {
res.sendFile(path.resolve('distApp', 'index.html'));
});
Ini adalah .jsx file. Perhatikan bagaimana jalan terpanjang datang pertama dan dapatkan's lebih umum. Untuk yang paling umum rute penggunaan yang tepat atribut.
// 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);
Mencoba sesuatu seperti ini.
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;
Bereaksi Router v5 sekarang memungkinkan anda untuk hanya mengarahkan menggunakan sejarah.push() berkat useHistory() hook:
``bej impor { useHistory } dari "bereaksi-router"
fungsi HomeButton() { biarkan sejarah = useHistory()
fungsi handleClick() { sejarah.push(" rumah") }
return (
Atau, anda dapat menggunakan withRouter
. Anda dapat mendapatkan akses ke sejarah
objek's sifat dan terdekat <Rute>
's pertandingan
melalui withRouter
higher-order komponen. withRouter
akan lulus diperbarui pertandingan
, location
, dan sejarah
alat peraga untuk dibungkus komponen setiap kali hal itu membuat.
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)
Atau hanya:
import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
"bereaksi": "^16.3.2", "bereaksi-dom": "^16.3.2", "bereaksi-router-dom": "^4.2.2"
Untuk menavigasi ke halaman lain (halaman Tentang dalam kasus saya), saya menginstal prop-jenis
. Kemudian saya impor dalam komponen yang bersangkutan.Dan saya menggunakan ini.konteks.router.sejarah.push('/tentang')
.Dan itu akan berlayar.
Kode saya adalah,
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
};
Untuk menavigasi ke komponen lain yang dapat anda gunakan ini.alat peraga.sejarah.push('/utama');
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
anda dapat menulis hoc untuk tujuan ini dan menulis metode panggilan mengarahkan, berikut adalah kode:
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;
Atau, anda dapat menggunakan Bereaksi bersyarat rendering.
`` impor { Komputer } dari "bereaksi-router"; impor Bereaksi, { Komponen } dari 'bereaksi';
kelas UserSignup meluas Komponen { konstruktor(alat peraga) { super(alat peraga); ini.negara = { redirect: palsu } } render() {