reactjs - 离开页面时如何清除状态
问题描述
我创建了一个测验应用程序,该应用程序在称为正确答案的状态下跟踪正确答案。问题是当用户离开一个测验并继续下一个测验时,测验答案仍然从上一个测验中存储。
我曾尝试使用 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.
解决方案
请记住,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>
}
推荐阅读
- python - Hive UDF 与 Python 错误代码返回代码 20001
- python - 如何使用 Beautiful Soup 获取元素的位置?
- java - Spigot忽略命令的第一个参数
- shell - 仅基于第 2 列对 csv 文件进行排序。如果第 2 列的 2 行相同,则应仅输入文件顺序。不应基于任何其他列进行排序
- haskell - 理解简单的 Haskell
- python - 如何使用 python 正则表达式将字符串转换为字典
- postgresql - 在 Postgres 中以 ddMMYYYY 格式在日期之间搜索
- c# - 如何在尝试添加到列表之前检查属性是否存在
- python - to_datetime 无法识别熊猫中的日期“2015 年 10 月 20 日”
- django - 为 Django 应用程序进行新迁移,忽略所有其他应用程序模型