这是我的notesSlice:
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
const url = "http://localhost:8000/";
const initialState = {
notices: [],
};
export const getNotices = createAsyncThunk(
"notices/getNotices",
async (_name, thunkAPI) => {
try {
const resp = await axios(`${url}notices`);
return resp.data;
} catch (error) {
return thunkAPI.rejectWithValue("something went wrong");
}
}
);
const noticesSlice = createSlice({
name: "notices",
initialState,
reducers: {
filterNotices: (state, { payload }) => {
console.log(state.notices)
console.log(payload)
if (payload.searchOption === "Simple") {
state.notices = state.notices.filter((note) =>
note.title.toLowerCase().includes(payload.search.toLowerCase())
);
} else if (payload.searchOption === "Advanced") {
state.notices = state.notices.filter(
(note) =>
note.description
.toLowerCase()
.includes(payload.search.toLowerCase()) ||
note.tags.filter((tag) => {
tag.toLowerCase().includes(payload.search.toLowerCase());
})
);
}
},
},
extraReducers: (builder) => {
builder
.addCase(getNotices.fulfilled, (state, { payload }) => {
state.notices = payload;
})
在filterNotice
方法的payload中,我正在发送带有search
输入和searchOption
的对象。我应该如何在每次调用filterNotice
方法时搜索所有通知?这是正确的方法吗?
1条答案
按热度按时间yc0p9oo01#
不要通过过滤来改变你的真理来源。过滤后的结果应该是从
notices
状态和search
值计算/导出的“状态”。如果不需要持久化过滤后的通知
将搜索类型和值存储在state中,并使用选择器函数计算派生的state。
UI将分派
setSearch
操作来更新搜索值,并使用useSelector
钩子和selectFilteredNotices
函数来选择过滤后的通知值。如果您确实需要将过滤后的通知持久化到状态
在state中创建一个新的
filteredNotices
数组,在分派filterNotices
操作时,您将过滤未更改的state.notices
数组并返回/更新state.filteredNotices
数组。这会使原始通知数据保持不变。