我正在尝试将用户资源的实例发布到我的项目中。当我不得不等到我重新启动项目才能看到新实例时,我注意到状态没有更新。在我的项目中,用户和资源之间存在多对多关系,其中 user_resource 作为连接。
尽管该实例已发布在我的后端,但它不会显示在前端。我的 POST fetch 似乎接收了正确的数据,甚至采取了正确的操作,但随后无法更新减速器中的任何内容。我认为这可能与我如何为减速器设置特定案例有关,尽管我不知道我做错了什么。当我使用调试器时,它会触发动作,但不会触发减速器。我尝试为 user_resources 创建一个完全独立的减速器,但这也不起作用。
fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: item.id,
user_id: this.props.users.id,
name: item.name,
description:item.description,
link:item.link,
})
})
.then(res => res.json())
.then(data2 => {
console.log(data2)
this.props.addUserResource(data2)
console.log(this.props)
debugger
})
}
let userInitialState = {
id: 0,
username: "",
name: '',
category: '',
token: "",
user_resources:[],
}
let userReducer = (state = userInitialState, action) => {
debugger
switch(action.type){
case "ADD_USERS":
let singleNestedObject = {
...action.users.user,
token: action.users.token
}
return {
...state,
username: action.users.user.username,
token: action.users.token,
id: action.users.user.id,
name: action.users.user.name,
category: action.users.user.category,
user_resources: action.users.user.user_resources
}
case "ADD_ONE_USER_RESOURCE":
let copyOfResources = [...state.users.user.user_resources, action.userResources]
debugger
console.log(...state.user_resources)
console.log(action.userResources)
console.log(copyOfResources)
return {
...state,
user_resources: action.userResources
}
default:
return state
}
}
export const addUserResource = (resourceInfo) => {
console.log("here")
return {
type: "ADD_ONE_USER_RESOURCE",
userResources: resourceInfo
}
}