1

我有一个在 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
  }

问题

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

4

1 回答 1

0

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

当用户点击浏览器上的后退按钮时。它会将他带到购物车页面。即 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

于 2020-06-03T15:59:42.740 回答