首页 > 解决方案 > 离开页面时如何清除状态

问题描述

我创建了一个测验应用程序,该应用程序在称为正确答案的状态下跟踪正确答案。问题是当用户离开一个测验并继续下一个测验时,测验答案仍然从上一个测验中存储。

我曾尝试使用 react-router-redux 中的 LOCATION_CHANGE,但我不确定我是否正确使用它。


    import { LOCATION_CHANGE } from "react-router-redux";
    const initialState = {
      questions: [],
      answers: [],
      correct_answer: []
    };

    export default function(state = initialState, action) {
      switch (action.type) {
        case "GET_QUESTIONS":
          return { ...state, questions: action.payload };
        case "GET_ANSWERS":
          return { ...state, answers: action.payload };
        case "CORRECT_ANSWER":
          return {
            ...state,
            correct_answer: [...state.correct_answer, action.payload]
          };
        case LOCATION_CHANGE:
          return {state = initialState};
        default:
          return state;
      }
    }```

The app needs to clear the correct_answers state anytime the user moves away from the page.

标签: reactjsreduxreact-redux

解决方案


请记住,redux 存储是一种无所不在的数据结构。无论您的应用程序中的任何 ui 更改如何,数据都会持续存在,其中包括组件中的本地状态更改和安装/卸载组件(除非您拆除减速器,但这根本不是您正在做的事情)。

如评论中所述,清除状态是您的工作。创建一个将重置减速器的操作。您如何实现它取决于您对测验组件的确切实现。

当您切换测验时,安装/卸载/道具更改如何工作?您是在安装一个全新的组件,还是将新数据输入到现有组件中?

如果下一个测验是一个全新的实例,则在卸载前一个测验时调用它:

componentWillUnmount() {
  this.props.resetQuizState() // your action that resets the data in your store
}

如果是同一个组件,但是传入了新的 props:

handleNextQuizClick() {
  this.props.resetQuizState()
  // and then rest of data manipulation/calling/parsing
}

render() {
  return (
    <button onClick={this.handleNextQuizClick}>
      next quiz
    </button>
}

推荐阅读