我能否在.then
中进行重定向,而不是使用console.log
?
axios
.post('/api/users/login', user)
.then(res => console.log(res.data))
.catch(err => this.setState({ errors: err.response.data }))
这是否可能,如果可能的话我该如何做?
我能否在.then
中进行重定向,而不是使用console.log
?
axios
.post('/api/users/login', user)
.then(res => console.log(res.data))
.catch(err => this.setState({ errors: err.response.data }))
这是否可能,如果可能的话我该如何做?
// Component code
import { browserHistory } from 'react-router';
class TestContainer extends React.Component {
auth = () => {
login()
.then(() => {
browserHistory.push("/addUser");
})
.catch(() => {
// Show alert to user;
})
}
render () {
return (
<div>
<button onClick={this.auth}>Auth</button>
</div>
);
}
}
// Action code
const login = () => {
return axios
.post('/api/users/login', user);
}
尝试导入错误:'browserHistory'未从'react-router'导出。
- Fiddle Freak您可以使用:location.window.href
通常我使用react-router进行重定向
history.js
import createHistory from 'history/createBrowserHistory';
export default createHistory()
Root.jsx
import { Router, Route } from 'react-router-dom'
import history from './history'
<Router history={history}>
<Route path="/test" component={Test}/>
</Router>
another_file.js
import history from './history'
history.push('/test') // this should change the url and re-render Test component
参考:https://github.com/ReactTraining/react-router/issues/3498
你的问题与reactjs或axios无关,它只是纯javascript。
使用location.href