我已经做了几个小时了。。我是redux和redux工具包的新手
我目前有一个注册表格,当我尝试注册时,它会更新我的后台,该后台使用mongoDB,但它不会在redux中更新我的状态,我无法理解。
appApi.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const appApi = createApi({
reducerPath: 'appApi',
baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:8001' }),
endpoints: builder => ({
signup: builder.mutation({
query: user => ({
url: '/users/signup',
method: 'POST',
body: user,
}),
}),
login: builder.mutation({
query: user => ({
url: '/users/login',
method: 'post',
body: user,
}),
}),
}),
});
export const { useSignupMutation, useLoginMutation } = appApi;
export default appApi;
userSlice.js
import { createSlice } from '@reduxjs/toolkit';
import appApi from '../services/appApi';
const initialState = null;
export const userSlice = createSlice({
name: 'users',
initialState,
reducers: {},
extraReducers: builder => {
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(_, { payload }) => {
console.log(_); // null why?
console.log(payload); //null why?
return payload;
}
);
builder.addMatcher(
appApi.endpoints.login.matchFulfilled,
(_, { payload }) => payload
);
},
});
export default userSlice.reducer;
编辑已解决
我发现了,我的前端是正确的,是我的后端错了。
这是在我的用户模型文件中。
我忘记在user.toObject末尾添加((;
我以前有什么
UserSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject; <----- this was the problem
delete userObject.password;
return userObject;
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(_, { payload }) => {
console.log(_); // null why?
console.log(payload); //null why?
return payload;
}
在这段代码中,_
是state
——在上面您将initialState
声明为null
——这就解释了null
。
至于有效负载,这很有趣,但老实说,我也不太相信这是null
,除非服务器明确返回它。也许可以看看完整的动作,看看发生了什么。
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(state, action) => {
console.log({state, action});
return action.payload;
}