reactjs - 将项目添加到数据库后更新 Redux 状态
问题描述
我还是个新手。我正在尝试构建一个小型全栈应用程序来跟踪项目中的时间。
我有一个带有 Postgresql 数据库的 Ruby on Rails API 和一个带有 Redux、Redux-React 和 Redux-thunk 的 React 前端,用于状态管理。所有 CRUD 功能在前端和后端之间都可以正常工作,但我无法在任何操作后更新 Redux 状态。
我的初始状态
{data: Array(2), included: Array(6)}
data: Array(7)
0:
attributes: {done: false, date: "2021-01-08", name: "Test3", customer: "Test3", sum_hours: 0}
id: "69"
relationships: {tasks: {…}}
type: "project"
__proto__: Object
1: {id: "70", type: "project", attributes: {…}, relationships: {…}}
2: {id: "71", type: "project", attributes: {…}, relationships: {…}}
3: {id: "72", type: "project", attributes: {…}, relationships: {…}}
4: {id: "73", type: "project", attributes: {…}, relationships: {…}}
5: {id: "1", type: "project", attributes: {…}, relationships: {…}}
6: {id: "5", type: "project", attributes: {…}, relationships: {…}}
length: 7
__proto__: Array(0)
included: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
__proto__: Object
这在成功 POST 到 db 后从动作传到我的减速器
{type: "ADD_NEW", data: {…}}
data:
attributes: {done: false, date: "2021-01-08", name: "Testi1", customer: "Testi1", sum_hours: 0}
id: "74"
relationships: {tasks: {…}}
type: "project"
__proto__: Object
type: "ADD_NEW"
__proto__: Object
我的减速机
const ProjectReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_NEW':
return Object.assign({}, state.data,
{
attributes: action.attributes,
id: action.id,
relationships: action.relationships
})
case 'DEL_PRO':
return state.data.filter(st => st.id != action.id)
case 'INIT_PROJECTS':
return action
default:
return state
}
}
export default ProjectReducer
我在我的减速器 ADD_NEW 上尝试了很多东西,你现在看到的只是最新的,无法更新状态。即使 DEL_PRO 也不起作用,当我在应用程序上发送我的删除时,它只是完全失去了状态。非常感谢所有帮助!
解决方案
我认为 state.data 是一个数组,所以你应该这样做:
case 'ADD_NEW':
return {
...state,
data: state.data.concat({
attributes: action.attributes,
id: action.id,
relationships: action.relationships,
}),
}
推荐阅读
- android - 我刚刚安装了 android studio 并且模拟器不工作 3.6.2
- python - 硒python元素不可交互错误
- c++ - 这两个数组有什么区别
- android - 如何根据分隔符将字符串拆分为 2 个不同的变量?
- python - 没有 reqparse.RequestParser() 的简单请求解析
- r - 将粗略的 R 控制台输出转换为 R 文件
- python - 在另一个函数的循环中时,Tkinter-python 按钮没有响应
- matlab - 如何从概率最小的数组中随机选择一个元素
- php - 如何解决数组到字符串转换错误?
- python - 如何正确地将数据扩充应用到 TFRecord 数据集?