在react.js中的重定向
在react.js中的重定向
我是react.js的新手。如何在登录后在react.js中进行重定向?这与Vue.js的路由有什么不同吗?我已经安装了这个包。我阅读了这个问题。我尝试过不同的方法,但都没有成功。
请问你能帮我提供一些基础代码或基础教程吗?
以下是我的代码:
import React, { Component } from 'react'; import Auth from '../services/Auth' import { Router, Route, Link, IndexRoute, hashHistory, browserHistory, Redirect } from 'react-router-dom' class Login extends Component { constructor(props) { super(props); this.state = {email: '',password:''}; this.handleChange = this.handleChange.bind(this); this.handleClick = this.handleClick.bind(this); } handleChange (event){ this.setState({[event.target.name]: event.target.value}); } handleClick(){ var data = { client_id: 2, client_secret: 'ispGH4SmkEeV4i5Tz9NoI0RSzid5mciG5ecw011f', grant_type: 'password', username: this.state.email, password: this.state.password } fetch('http://127.0.0.1:8000/oauth/token', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(data) }) .then((response) => response.json()) .then((responseData) => { Auth.setToken(responseData.access_token,responseData.expires_in+ Date.now()); this.props.history.push("/dashboard"); }) } } export default Login;
我得到的错误如下
在使用react.js中,出现了一个问题,即重定向(Redirect)的问题。问题的原因是组件不完整,如果使用的是react-router v4版本,那么组件应该被包裹在withRouter中,这样可以将history属性传递给组件。请确认一下history属性是否不为undefined。
如果问题没有被理解错的话,对不起。我已经更新了问题,这样对你会有帮助。谢谢。
是的。将组件包裹在withRouter中将解决这个问题。如果没有解决,请告诉我,我可以为你创建一个示例来帮你理解流程。
谢谢。我该怎么做呢?
我创建了一个示例来演示react-router的工作原理。你可以在codesandbox.io/s/qlmrxorl66上进行试验。同时,我建议你阅读一下官方文档。如果我回答了你的问题,请将其标记为答案。:)
在React.js中,有两种方式可以实现重定向(redirect)。
一种是使用react-router-dom中的重定向(redirect)功能。
另一种是使用第三方库history来实现重定向(redirect)(这是你正在使用的方式)。
如果在props中找不到history属性,则需要使用withRouter。
示例代码如下:
import { withRouter } from 'react-router-dom' class Login extends React.Component { handleSubmit = (user) => { saveUser(user).then(() => this.props.history.push('/dashboard') ) } render() { return () } } export default withRouter(Login)Register
详细信息请参考: