如何在axios中进行重定向?

4

我能否在.then中进行重定向,而不是使用console.log

axios
  .post('/api/users/login', user)
  .then(res => console.log(res.data))
  .catch(err => this.setState({ errors: err.response.data }))

这是否可能,如果可能的话我该如何做?


重定向到另一个页面还是基于响应? - jsDevia
我认为你的问题与axios无关。 你可以使用这个 => location.href - jsDevia
并且reactjs标签不相关。 - jsDevia
我只想在登录后重定向到'/'。 - Anelia Kostadinova
这是关于编程的内容,需要将其从英语翻译成中文。请仅返回已翻译的文本:这不涉及ReactJS或Axios,只是纯JavaScript。你可以使用我的解决方案。 - jsDevia
3个回答

3
我建议您不要在操作(在这种情况下是axios调用)中执行副作用。这是因为您最终会将这些调用添加到redux thunk/saga或其他中间件中。
我遵循的模式是返回承诺并在组件(或容器)中添加重定向逻辑。以下是其好处:
1. 它使您的代码更清洁,避免API调用内部的副作用。 2. 使用模拟数据更容易测试您的API调用。 3. 在未传递回调函数参数的情况下显示API失败的警报。
话虽如此,您可以按以下方式使用上述逻辑:
// 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);
}

1
我遇到了以下错误:尝试导入错误:'browserHistory'未从'react-router'导出。 - Fiddle Freak

1

您可以使用: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


0

你的问题与reactjs或axios无关,它只是纯javascript。

使用location.href


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接