【发布时间】:2022-01-05 19:49:36
【问题描述】:
我正在尝试删除redux工具包中的项目,但不知道如何,删除功能仅在屏幕上起作用,我必须按两次才能删除前一个,
这里是减速器
const noteReducer = createSlice({
name: "note",
initialState: NoteList,
reducers: {
addNote: (state, action: PayloadAction<NoteI>) => {
const newNote: NoteI = {
id: new Date(),
header: action.payload.header,
note: action.payload.note,
date: new Date(),
selectStatus: false,
};
state.push(newNote);
},
removeNote: (state, action: PayloadAction<NoteI>) => { //
======> Problem here
return state.filter((item) => item.id !== action.payload.id);
},
toggleSelect: (state, action: PayloadAction<NoteI>) => {
return state.map((item) => {
if (item.id === action.payload.id) {
return { ...item, selectStatus: !item.selectStatus };
}
return item;
});
},
loadDefault: (state) => {
return state.map((item) => {
return { ...item, selectStatus: false };
});
},
resetNote: (state) => {
return (state = []);
},
editNote: (state, action: PayloadAction<NoteI>) => {
return state.map((item) => {
if (item.id === action.payload.id) {
return {
...item,
note: action.payload.note,
header: action.payload.header,
date: action.payload.date,
};
}
return item;
});
},
},
extraReducers: (builder) => {
builder.addCase(fetchNote.fulfilled, (state, action) => {
state = [];
return state.concat(action.payload);
});
},
});
这是我使用它的功能:
export default function NoteList(props: noteListI) {
const { title, note, id, date } = props;
const data = useSelector((state: RootState) => state.persistedReducer.note);
const removeSelectedNote = () => {
dispatch(removeNote({ id: id }));
console.log(data); ====> still log 4 if i have 4
};
return (
<View>
<TouchableOpacity
onLongPress={() => {
removeSelectedNote();
}}
// flex
style={CONTAINER}
onPress={() =>
!toggleSelectedButton ? onNavDetail() : setEnableToggle()
}
>
<Note
note={note}
header={title}
date={date}
id={id}
selectedStatus={selectedButtonStatus}
/>
</TouchableOpacity>
</View>
);
}
我必须按两次才能使其工作,例如,我有 4 个项目,当我按一个时,屏幕上的项目消失但数据日志仍然有 4 个项目,当我单击另一个时,它在控制台上显示 3 .log 但屏幕显示 2,我的意思是该功能可能正常工作,但我也想更新状态,我该怎么做? 或者如果我删除了 redux-toolkit 中的项目,我该如何更新状态?
这是一个 gif 来展示发生了什么
更新
正如@Janik 所建议的,我在函数中使用了 console.log,所以它记录正确
但我怎样才能得到这个改变?我的意思是,它记录正确,但我是从 firebase 获取数据,所以我需要记录这些数据以对 firebase 进行更改,所以我该怎么做那,我试着把它放在一个函数中:
const getNote = useCallback(() => {
setCurrentNote(data);
}, [data]);
但它显示此错误:
ExceptionsManager.js:184 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
【问题讨论】:
标签: javascript reactjs react-native redux react-redux