[英]Delete item with redux
Im trying to delete messages written in a form with react and redux.我试图删除用 react 和 redux 形式编写的消息。
The id props is sent correctly as I can see in console, but I only get my error msg when I press the delete button.正如我在控制台中看到的那样,id 道具已正确发送,但是当我按下删除按钮时,我只会收到错误消息。
This is the button component:这是按钮组件:
import React from 'react'
import { useDispatch } from 'react-redux'
import { messages, fetchDeleteMessage } from 'reducer/messages'
export const DeleteBtn = (props) => {
const dispatch = useDispatch()
const handleDeleteMessageClick = () => {
dispatch(fetchDeleteMessage(props.message.id))
console.log('delete message', (props.message.id))
}
return (
<button className="delete-btn"
onClick={handleDeleteMessageClick}>
<span role="img" aria-label="delete">✖︎</span>
</button>
)
}
This is my reducer where I try to fetch and delete a specific message upon its id, the id is passed on to the fetch correctly, but nothing happens and I cant see whats wrong and feel I tried it all (....apparently not)这是我的减速器,我尝试在其 id 上获取和删除特定消息,id 正确传递给 fetch,但没有任何反应,我看不出有什么问题,感觉我都试过了(....显然不是)
import { createSlice } from '@reduxjs/toolkit'
export const messages = createSlice({
name: 'messages',
initialState: {
allMessages: [],
},
reducers: {
deleteMessage: (state, action) => {
console.log('deleteMessageState', state)
console.log('deleteMessageAction', action)
//finds the task
//remove it from the array
state.allMessages = state.allMessages.filter((message) => message.id !== action.payload)
},
}
})
//****** fetch DELETE message ********
export const fetchDeleteMessage = (id) => {
return (dispatch) => {
fetch(`http://localhost:3004/messages/${id}`, {
method: 'DELETE',
statusCode: 204,
headers: {
'Content-Type': 'application/json'
}
})
.then((res) => res.json())
.then(json => {
console.log('DELETE', json, id)
dispatch(messages.action.deleteMessage(id))
})
.catch(err => {
console.error('error', err)
dispatch(messages.actions.deleteMessage({ error: `Error, failed to delete` }))
})
}
}
`````
To delete an item you should return state要删除一个项目,您应该返回 state
return state.allMessages.filter((message) => message.id !== action.payload)
instead of代替
state.allMessages = state.allMessages.filter((message) => message.id !== action.payload)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.