【问题标题】:How to clear a redux store completely? Browser back button restores the store如何彻底清除一个redux store?浏览器后退按钮恢复存储
【发布时间】:2020-09-21 19:48:14
【问题描述】:

我有一个在 redux 商店中有购物车的应用程序。当用户完成购买时。移出最终页面时,我重置(redux 存储)购物车。 但是当用户点击浏览器后退按钮时。 redux store 恢复了之前的数据。 如何彻底清除 redux store?购买无需登录/注册。我正在将 Reactjs 与 Redux(使用 redux-thunk)一起使用。

当用户点击后退按钮时 - (不要转到上一页,即再次付款页面)

  componentDidMount () {
    window.onpopstate = this.onBackButtonEvent
  }

onBackButtonEvent = (e) => {
        e.preventDefault()
        console.log('in backbutton')
        this.props.history.push('/insta-repair')
        this.props.resetCart()
        window.onpopstate = () => {}
      }

购物车操作

export const resetCart = () => ({
  type: cartActionTypes.RESET_CART,
  data: []
})

推车减速器

case CartTypes.RESET_CART:
  return {
    ...initialState,
    item: action.data
  }

问题

当用户点击浏览器后退按钮时。然后可以访问Previous redux store 数据。有没有办法完全重置商店?

【问题讨论】:

标签: reactjs redux redux-store


【解决方案1】:

我的问题中的代码已经清除了 Redux 存储。这里的问题是,当 url 中存在 cart_id 时,它会向服务器发出请求,这会再次获取 redux 存储数据。

当用户点击浏览器上的返回按钮时。它会将他带到购物车页面。 IE。 www.mysite.com/cart/id 并且这个 url 会向服务器请求数据并再次将其存储在 redux 存储中。

我想确保 redux 存储在 root reducer 级别被清除。所以我使用了这个答案中的代码https://stackoverflow.com/a/35641992/6555647

const reducers= combineReducers({
  config: config,
  cart: cartReducer,
  shop: shop
})

const rootReducer  = (state, action) => {
  if (action.type === 'RESET_CART') {
    state = undefined; // this will set the state to initial automatically
  }
  return reducers(state, action);
}
export default rootReducer;

您可以在任何地方发送 'RESET_CART 操作。

后退按钮问题

我曾经将用户重定向到订单跟踪页面。我使用 history.replace()

而不是 history.push()
this.props.history.replace({
    pathname: `${BASE_URL}/success/${orderNumber}`,
    orderNumber: orderNumber
})

你可以这样做

this.props.history.replace(`${BASE_URL}/success/${orderNumber}`)

如果您不想将 orderNumber 推送到新安装组件的状态

history.replace('/route') will replace your current route with a new given route

如果用户回击,他是否会在同一页面上。如果他不会重定向到上一页。 如果再次点击返回按钮。他会去主页。我在 OrderNumber 组件中为此添加了代码。

  componentDidMount () {
    window.onpopstate = this.onBackButtonEvent
  }
  onBackButtonEvent = (e) => {
    e.preventDefault()
    console.log('in backbutton')
    this.props.history.push('/insta-repair') //homepage route.
    this.props.resetCart()
    window.onpopstate = () => {} // reset the onpopstate
  }

记得重置 window.onpopstate,否则每个后退按钮事件都会转到应用中每个组件的同一页面。

在此处阅读有关历史对象的更多信息 - https://reacttraining.com/react-router/web/api/history

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2021-01-10
    相关资源
    最近更新 更多