Reactjs从动作重定向

时间:2018-05-07 13:24:11

标签: reactjs redirect react-router

我正在尝试实施反应路由器版本4.请找到我现在的最小代码,如下所示:

import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import { Menu, MenuItem } from '@progress/kendo-layout-react-wrapper';
import { Switch } from 'react-router-dom';

export default () => (
    <BrowserRouter>
        <div>
            <div className="col-xs-12 col-sm-6 col-md-12">
                <header className="App-header">
                    <h1 className="App-title">TestUsers</h1>
                </header>
                <Menu>
                    <MenuItem>
                        <Link to="/users">Users</Link>
                    </MenuItem>
                    <MenuItem>
                        Shelves
                        </MenuItem>
                    <MenuItem>
                        Products
                    </MenuItem>
                </Menu>
            </div>
            <Switch>
                <Route exact path="/users" component={Users} />
                <Route exact path="/users/add" component={Users} />
                <Route exact path="/users/:id" component={Users} />
            </Switch>
        </div>
    </BrowserRouter>
)

我已成功添加用户。我想从添加用户的操作重定向到用户的列表页面。请在下面找到行动代码:

export function addUser(objData) {
    return function (dispatch) {
        axios.post(
            'http://localhost:4000/api/v1/users',
            {
                'name': objData.name,
                'email': objData.email
            }
        )
            .then((response) => {
                dispatch({ 'type': ADD_USER, 'payload': true });
                // TODO: programmatically redirect using react-router v4
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

我一直在努力实现同样的目标。任何人都可以指出我正确的方向。

由于

5 个答案:

答案 0 :(得分:0)

你可以从你的行动中返回Promise:

export function addUser(objData) {
    return function (dispatch) {
        return axios.post(
            'http://localhost:4000/api/v1/users',
            {
                'name': objData.name,
                'email': objData.email
            }
        )
            .then((response) => {
                dispatch({ 'type': ADD_USER, 'payload': true });
                // TODO: programmatically redirect using react-router v4
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

然后在一个组件中:

componentDidMount(){
  this.props.addUser(objData).then(() => {
    this.props.history.push('/somwhere')
  })
}

答案 1 :(得分:0)

在发送操作后使用this.props.history.push('/some/path')

我还建议你检查response.status是否等于200

答案 2 :(得分:0)

您可以使用历史记录模块。

创建history.js文件

//history.js
import createHistory from 'history/createHashHistory'
export default createHistory()

使用新历史记录更新路由器。您需要使用Router而不是BrowserRouter。

import React from 'react';
import { Router, Route, Link } from 'react-router-dom';
import { Menu, MenuItem } from '@progress/kendo-layout-react-wrapper';
import { Switch } from 'react-router-dom';
import history from './history';

export default () => (
    <Router history={history}>
       ...
    </Router>
);

现在您可以通过编程方式进行导航。

import history from './history'
export function addUser(objData) {
    return function (dispatch) {
        axios.post(
            'http://localhost:4000/api/v1/users',
            {
                'name': objData.name,
                'email': objData.email
            }
        )
            .then((response) => {
                dispatch({ 'type': ADD_USER, 'payload': true });
                // TODO: programmatically redirect using react-router v4
               history.push(path)
            })
            .catch((error) => {
                console.log(error);
            });
    }
}

答案 3 :(得分:0)

在react-router 4中,引入了<Redirect />组件,它以render()方法返回,以实现您的需要。重定向组件也是从react-router-dom导入的,因此:import { BrowserRouter, Route, Link, Redirect } from 'react-router-dom';

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/>;
}

答案 4 :(得分:0)

您可以使用回拨

export function addUser(objData, onSuccess, onFail) {
    return function (dispatch) {
        return axios.post(
            'http://localhost:4000/api/v1/users',
            {
                'name': objData.name,
                'email': objData.email
            }
        )
            .then((response) => {
                dispatch({ 'type': ADD_USER, 'payload': true });
                onSuccess()
            })
            .catch((error) => {
                //you can handle error on your component
                onFail(error);
            });
    }
}

然后在组件上调用addUser

addUser(
   objData,
   () => this.props.history.push('/your-user-list-component'),
   () => {// handle the error here.}
)
相关问题