从apiCall中删除项目需要重新加载页面才能从客户端删除



我使用redux工具包与react native和mongodb (mongoose)我删除项目,它成功地从数据库中删除但不是在客户端,需要重新加载页面todoSlice:

import {createSlice} from '@reduxjs/toolkit';
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state
},
},
});
export const {deleteTodo} = todoSlice.actions;
export default todoSlice.reducer;

api调用:

import axios from 'axios';
import {deleteTodo} from './todoSlice';
export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo());
} catch (err) {
console.log(err);
}
};
主:

const {todo} = useSelector(state => state);
const dispatch = useDispatch();
const {todos} = todo;
useEffect(() => {
getTodos(dispatch);
}, []);
const handleDelete = id => {
deleteOneTodo(id, dispatch);
};

您必须在todoSlice中实现deleteTodo,以便从本地状态中删除已删除的id,

...
export const todoSlice = createSlice({
name: 'todos',
initialState: {
todos: [],
pending: null,
error: null,
},
reducers: {
deleteTodo: (state, action) => {
return state.filter((todo)=>todo.id!==action.payload.id);
},
},
});
...

当然,你必须传递有效载荷与你想要删除的todo的id

export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
dispatch(deleteTodo({id:id}));
} catch (err) {
console.log(err);
}
};

如果你仍然有疑问,你可以按照这个教程:https://www.youtube.com/watch?v=fiesH6WU63I

我只是在'deleteOneTodo'中调用'getTodos'并从reducer中删除deleteTodo我希望这是一个好的实践

export const deleteOneTodo = async (id, dispatch) => {
try {
await axios.delete(`http://10.0.2.2:5000/todos/${id}`);
// i add this line => 
getTodos(dispatch);
} catch (err) {
console.log(err);
}
};

相关内容

  • 没有找到相关文章

最新更新