我正在学习React路由器,我似乎不知道目前推荐的重定向方法是什么。我读过很多文章和StackOverflow文章,但种类太多了,所以我不确定要为Reactive路由器的当前版本实现哪一种。
我要做的是使用axios在AJAX调用之后重定向。
axios.post('/some-route')
.then(/*I want to redirect here*/)注意:这段代码驻留在一个函数中,在一个React.Component中,它在提交表单时被调用。
我怎样才能做到这一点?
请告诉我你需要什么细节。
发布于 2017-06-20 14:25:54
您可以使用browserHistory:
import { browserHistory } from "react-router";
browserHistory.push({
pathname: '/your/path'
});发布于 2017-06-20 14:27:18
这个答案是针对
react-router-v4的。
如果您想要从相同的redirect (而不是来自某个action)中呈现这个component,并且这个component是由某个route呈现的,那么您可以使用在props中传递的history对象。
componentDidMount(){
if(this.state.some_param){
this.props.history.push("/some_location")
}
}最好的方法是创建您自己的history对象。您可以在任何history中使用这个action对象。
//history.js
import createHistory from 'history/createBrowserHistory'
export default createHistory()然后你可以在路由器中使用这个历史记录,
import history from "./history"
<Router history = {history}>
//other code
</Router>现在您可以在任何地方使用这个历史对象重定向,
axios.post('/some-route')
.then(res=>{
history.push("/some_location")
})
const {Component} = React
const {render} = ReactDOM
const {Router, Link, Route, Switch, withRouter, Redirect} = ReactRouterDOM
const createHistory = History.createHashHistory
const myhistory = createHistory()
class App extends Component{
redirectToHome(){
myhistory.push("/home")
}
redirectToAbout(){
myhistory.push("/about")
}
render(){
return(
<div>
<Route path = "/home" component = {Home} />
<Route path = "/about" component = {About} />
<button onClick = {this.redirectToHome}>Redirect to home</button>
<button onClick = {this.redirectToAbout}>Redirect to about</button>
</div>
)
}
}
const Home = ()=>{
return(
<div>
Home
</div>
)
}
const About = ()=>{
return(
<div>About</div>
)
}
render(<Router history = {myhistory}><App/></Router>, document.getElementById('app'))<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<script src="https://unpkg.com/react-router-dom@4.1.1/umd/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/history/4.6.3/history.min.js"></script>
<div id="app"></div>
发布于 2017-06-20 14:54:00
从React路由器v4开始,browserHistory不再从react-router导出。
你有两种可能性。
1)如果您的组件是通过路由(是component组件的<Route>支柱)呈现的,那么您将自动获得一些对象作为支持:
然后,可以在组件的上下文中使用this.props.history.push("/some_location")。
2)如果组件与特定路由无关,则可以使用withRouter高级组件(它是react-router的一部分)获得相同的支持
import { withRouter } from "react-router-dom";
const Component = ( { history, location, match } ) => (
// your component code
);
export default withRouter(Component);
https://stackoverflow.com/questions/44655661
复制相似问题