在React和Redux中删除页面/路由后进行重定向

时间:2018-10-17 16:45:22

标签: javascript reactjs react-redux react-router

作为使用react,react-router和redux的实践,我正在制作一个非常小的应用程序,它具有两个模型:吸尘器和存储。在我的应用中,您可以看到所有吸尘器,所有商店,单个吸尘器或单个商店。您可以在单个页面视图中添加和删除吸尘实例并进行存储。

我遇到的问题是,删除吸尘器或存储后,我的应用程序中断了,因为该路由不再存在。

我尝试添加一个NotFound组件和路由,但是因为我在路由(/ vacuums /:id)中使用了变量,所以它确实到达了那里。

<Switch>
   <Route exact path="/stores" component={Allstores} />
   <Route exact path="/stores/add" component={storesAddForm} />
   <Route exact path="/stores/:storeId" component={Singlestores} />
   <Route exact path="/vacuums" component={Allvacuums} />
   <Route exact path="/vacuums/add" component={vacuumsAddForm} />
   <Route exact path="/vacuums/:vacuumsId" component={Singlevacuums} />
   <Route component={NotFound} />
</Switch>

使用redux删除功能:

export const REMOVE_VACUUM = 'REMOVE_VACUUM';

export const removeVacuum = vacuumId => {
  return {
    type: REMOVE_VACUUM,
    vacuumId: vacuumId,
  };
};

const deleteVacuum = id => {
    return async (dispatch, getState) => {
       const deleted = await axios.delete(`/api/allVacuums/${id}`);
       dispatch(removeVacuum(id));
    };
};

const rootReducer = (state = initialState, action) => {
      switch (action.type) {
        case REMOVE_VACUUM:
             const arr = state.vacuums.filter(
                   vacuum => vacuum.id !== action.vacuumId
                   );
             return { ...state, vacuums: arr };
      }
}

1 个答案:

答案 0 :(得分:0)

由于您正在使用redux,因此从Singlevacuums组件将this.props.history从组件传递到deleteVacuum动作创建者:

import React, { PureComponent } from 'react';
import { deleteVacuum } from '../actions/vacuumActions';

class Singlevacuums extends PureComponent {

  handleClick = id => {
    const { deleteVacuum, history } = this.props;

    deleteVacuum(id, history); // delete vacuum action action creator
  }

  render = () => (
    <div>
    {this.props.vacuums.map(({ id }) => (
      <button id={id} onClick={() => this.handleClick(id)}>Delete Vacuum</button>
    ))}
    </div>
  )
}

export default connect(state=> ({ vacuums: state.vacuums }), { deleteVacuum })(Singlevacuums)

然后在您的动作创建者中(总是try/catch兑现您的诺言,否则,当他们兑现失败时-他们将会兑现-您的应用程序不会崩溃!!)

const deleteVacuum = (id, history) => async dispatch => {
    try {
       await axios.delete(`/api/allVacuums/${id}`); // remove vacuum from API
       dispatch(removeVacuum(id)); // remove vacuum from redux state
       history.push('/'); // redirect user to "/" or where ever 
    catch (err) {
       console.error(err);
    }
};