简体   繁体   English

React redux:如何在按下后退按钮时清除 redux 商店 state

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

I am using react redux combination with following structure:我正在使用具有以下结构的 react redux 组合:

<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.如果我在 /abc/add 页面上并单击浏览器后退按钮,它不会清除商店,但如果我刷新页面后它会清除商店。 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.可以使用useEffect cleanup function 或componentWillUnmount function 来清除 redux Z967339E2EA99AZEF858。

For example:例如:

store.js 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 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在 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然后像这样设置你的 reducer.js 文件

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

then invoke onButtonReset() like this然后像这样调用 onButtonReset()

onClick = () => onButtonReset();

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

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