[英]React redux: how to clear the redux store state on back button press
[英]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.