繁体   English   中英

如何彻底清除 redux 商店? 浏览器后退按钮恢复存储

[英]How to clear a redux store completely? Browser back button restores the store

我有一个在 redux 商店中有购物车的应用程序。 当用户完成购买时。 移出最终页面时,我重置(redux 存储)购物车。 但是当用户单击浏览器后退按钮时。 redux 存储返回之前的数据。 如何彻底清除 redux 商店? 购买无需登录/注册。 我正在使用 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
  }

问题

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

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

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

我想确保 redux 存储在根减速器级别被清除。 所以我使用了这个答案中的代码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 推送到新安装组件的 state

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

如果用户回击,他是否会在同一页面上。 如果他不会重定向到上一页。 如果再按返回键 他将 go 到主页。 我在 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否则每个后退按钮事件将在您的应用程序中的每个组件上进入同一页面。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM