reactjs 更新有效负载后状态未更新?

rqenqsqc  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(145)

在从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中。有人知道是什么导致了这种行为吗?

2skhul33

2skhul331#

使用memo将导致React跳过渲染组件,如果其 prop 没有更改。
在这里我可以看到,在dispatch(editNote(...))之后,你正在更新noteInputeditId,所以它不应该是因为React.memo
看起来editNoteasync,在这里,您正在等待传入数据之前调度操作,所以这应该是问题,尝试这样做:

const handleSaveNote = async () => {
 //...
 await dispatch(editNote({ id: editId, content: noteInput }));
}

相关问题