在从EntityAdapter
调用.updateOne
之后,当我调用useAppSelector
来获取状态时,我的状态似乎没有用最新的有效负载更新。我总是得到旧的价值观。
以下是我的代码:
export const privateNotesSlice = createSlice({
name: "privateNotes",
initialState,
reducers: {
noteEdited(state, action: PayloadAction<{ id: EntityId, content: string }>) {
privateNotesAdapter.setOne(state, action.payload)
},
noteDeleted(state, action: PayloadAction<EntityId>) {
privateNotesAdapter.removeOne(state, action.payload)
},
},
extraReducers: (builder) => {
builder
...
.addCase(editNote.fulfilled, (state, action) => {
console.log(action.payload) //this returns the new payload
privateNotesAdapter.updateOne(state, action.payload) //doesnt seem to be updating
})
}
});
export const editNote = createAsyncThunk<
Update<PrivateNote>,
PrivateNote,
{
rejectValue: requestError
}
>("privateNotes/editNote", async (existingNote: PrivateNote, thunkAPI: any) => {
try {
const state = store.getState()
const { content, id } = existingNote;
await serveraxios.post(
`/note/${id}`,
{ content },
{
// withCredentials: true,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${state.auth.auth.accessToken}`
}
}
);
const payload = { id, content }
console.log(payload)
return payload
} catch (error: any) {
return thunkAPI.rejectWithValue({
status: error.response.data.status,
message: error.response.data.message,
});
}
});
例如,当我调用父组件中的dispatch(editNote(...))
来更新状态时,切片中的action.payload
显示它是新值。但是当我试图在子组件中获取相同的状态时,它不会返回更新后的值。
//parent component
const PrivateNoteList: React.FC = () => {
const privateNoteIds = useAppSelector(selectPrivateNoteIds)
const dispatch = useAppDispatch()
...
const handleClose = () => setOpen(false);
const handleSaveNote = () => {
if (editId !== null) {
dispatch(editNote({ id: editId, content: noteInput }))
} else {
dispatch(addNote(noteInput))
}
setNoteInput('')
setEditId(null)
handleClose()
}
...
//child component:
const PrivateNoteExcerpt: React.FC<PrivateNoteExcerptProps> = React.memo(({ privateNoteId, setEditId, setNoteInput, handleOpen, index }) => {
const number = index + 1
const privateNote = useAppSelector(state => selectPrivateNoteById(state, privateNoteId))
const dispatch = useAppDispatch()
console.log(privateNote); //I dont get the updated value
...
我也不确定这是否是由于我的子组件也被 Package 在React.memo
中。有人知道是什么导致了这种行为吗?
1条答案
按热度按时间2skhul331#
使用memo将导致React跳过渲染组件,如果其 prop 没有更改。
在这里我可以看到,在
dispatch(editNote(...))
之后,你正在更新noteInput
和editId
,所以它不应该是因为React.memo
。看起来
editNote
是async
,在这里,您正在等待传入数据之前调度操作,所以这应该是问题,尝试这样做: