简体   繁体   中英

React redux: how to clear the redux store state on back button press

I am using react redux combination with following structure:

<div>
  // Material ui autocomplete component which sets value in redux store
  <Switch>
  <Route exact path="/abc"><CompA/></Route>
<Route path="/abc/add"><CompB/></Route>
</Switch>
</div>

If I am on /abc/add page and I click on browser back button it is not clearing the store but if I refresh the page after that it clears the store. How can I clear it on back button press?

Thanks in advance.

You can use useEffect cleanup function or componentWillUnmount function to clear redux state.

For example:

store.js

export const resetStore = () => ({
  type: STORE_NAME_RESET
});

export default function reducer(state = initialState, action) {
  switch(action.type) {
    case STORE_NAME_RESET:
      return initialState;
    default:
      return state;
  }
}

CompB.js

// React hooks

const CompB = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    return dispatch(resetStore());
  }, []);

  return <div></div>;
};

// React class component

class CompB extends React.Component {
  componentWillUnmount() {
    this.props.resetStore();
  }
}

export default connect(null, { resetStore })(AddTodo)

you can try this; set the action you want the back button to perform in action.js

export const RESET_ON_BACK_BUTTON = "RESET_ON_BACK_BUTTON"; 
export const onButtonReset = () => ({
type: RESET_ON_BACK_BUTTON,
});

then set your reducer.js file like this

case RESET_ON_BACK_BUTTON:
      return {
        ...state,
        backToPreviousPageInProgress: false,
        previousPageData: null,
      };

then invoke onButtonReset() like this

onClick = () => onButtonReset();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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