reactjs - 在网站的多个页面上具有相同对象名称的道具
问题描述
我试图了解如何准确地从道具中保留数据。
我的例子是:
- 我打开第 1 页并使用 Automat 对象获取道具。
- 我转到第 2 页,也使用 Automat 对象获取道具,但它们是不同的(其他操作)。
问题是当我转到第 2 页或任何其他页面时,第一页的道具仍然存在并且我的数据是错误的。在这种情况下,摆脱它们的唯一方法是刷新页面或调用函数,但这是错误的方法。在这种情况下,我应该以某种方式首先删除第 1 页 Automat Props,或者可能在每个页面调用上获取具有唯一名称的 Props(但我认为这是没有意义的)?
我从 Java (SpringBoot) 和 Hibernate 获取数据。
第 1 页
////// 获取所有自动机 - 返回数据库中所有自动机的列表
componentDidMount() {
this.props.getAutomats();
}
export const getAutomats = () => async (dispatch) => {
const res = await axios.get("/api/automat/all");
dispatch({
type: GET_AUTOMATS, //typ reducera
payload: res.data, //dane z bazy
});
};
示例
[
{
"id": 1,
"name": "zimny jeden",
"serialNumber": "123456",
"type": "2",
"deleted": 0,
"status": null,
"productionDate": null,
"fundsDrawns": []
},
{
"id": 2,
"name": "",
"serialNumber": "",
"type": "Zimny",
"deleted": 0,
"status": null,
"productionDate": "2021-00-08",
"fundsDrawns": []
}
]
然后转到第 2 页
////// 获取所有未使用的自动机
componentDidMount() {
this.props.getAutomatFree();
}
export const getAutomatFree = () => async (dispatch) => {
const res = await axios.get("/api/automat/all/free");
dispatch({
type: GET_AUTOMATS, //typ reducera
payload: res.data, //dane z bazy
});
};
示例
[
{
"id": 1,
"name": "zimny jeden",
"serialNumber": "123456",
"type": "2",
"deleted": 0,
"status": null,
"productionDate": null,
"fundsDrawns": []
}
]
两个页面都返回 Objects 类型 Automats 的道具,但是当我从第 1 页转到第 2 页时,我看到两个甚至三个 Automats(第 1 页和第 2 页的总和)而不是一个。
编辑:减速机
import { GET_AUTOMAT, GET_AUTOMATS, DELETE_AUTOMAT } from "../actions/types";
const initialState = {
automats: [], //array
automat: {} //single
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_AUTOMATS:
//...state - Adds old state properties to the new object by copying
return {
...state,
automats: action.payload // dane z listą projektów, które zaktualizują state
};
case GET_AUTOMAT:
return {
...state,
automat: action.payload
};
case DELETE_AUTOMAT:
return {
//jeżeli delete się uda to ma odświeżyć poprzez odfiltrowanie usuniętego obiektu
//zwraca do wyswietlenia projekty sprzeczne z action.payload (id do skasowania)
...state,
automats: state.automats.filter(
automat => automat.serialNumber !== action.payload
)
};
default:
return state;
}
}
解决方案
推荐阅读
- powershell - Posh-ssh 是否不适用于 Windows 任务计划程序
- mapbox-gl-js - querySourceFeature 返回空数组
- python - 允许用户输入单词的列表位置以返回列表中的第二个和第三个元素
- html - 如何在单击角度 7 中的按钮时在表格中添加新行
- angular - ngrx-data 选择单个实体
- amazon-web-services - 在 AWS 中使用 S3 listObjectVersions 需要什么权限?
- sql - 如何将值从一列连接到另一列
- regex - 从字符串中检索持续时间(以秒为单位)
- html - 悬停时如何突出显示 sap.m.table 单元格的边框?
- mysql - 根据匹配多个列值的条件选择数据