我正在尝试使用 Redux Toolkit 和 TypeScript 实现身份验证。首先,我像这样使用 createAsyncThunk 创建注册。
const signUp = createAsyncThunk<
string | null,
{
name: string;
email: string;
password: string;
avatar: string;
}
>(
"user/signup",
async ({ name, email, password, avatar }, { rejectWithValue }) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
await axios.post(
`${backendURL}/api/user/register`,
{ name, email, password, avatar },
config
);
return null;
} catch (error: any) {
if (error.response && error.response.data.message) {
return rejectWithValue(error.response.data.message);
} else {
return rejectWithValue(error.message);
}
}
}
);
const signIn = createAsyncThunk<void, { email: string; password: string }, {}>(
"user/signin",
async ({ email, password }, { rejectWithValue }) => {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const { data } = await axios.post(
`${backendURL}/api/user/signin`,
{ email, password },
config
);
localStorage.setItem("userToken", data.userToken);
return data;
} catch (error: any) {
if (error.response && error.response.data.message) {
return rejectWithValue(error.response.data.message);
} else {
return rejectWithValue(error.message);
}
}
}
);
然后是减速机
const initialState: {
userToken: string | null;
loading: boolean;
userInfo: { userId: string; email: string } | null;
error: string | null;
success: boolean;
} = {
userToken,
loading: false,
userInfo: null,
error: null,
success: false,
};
const authSlice = createSlice({
name: "authen",
initialState,
reducers: {
logout: (state) => {
localStorage.removeItem("userToken");
state.loading = false;
state.userInfo = null;
state.userToken = null;
state.error = null;
},
setCredentials: (state, { payload }) => {
state.userInfo = payload;
},
},
extraReducers: (builder) => {
builder
.addCase(signUp.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(signUp.fulfilled, (state) => {
state.loading = false;
state.success = true;
})
.addCase(signUp.rejected, (state, action) => {
state.loading = false;
state.error = action.payload;
})
.addCase(signIn.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(signIn.rejected, (state, { payload }) => {
state.loading = false;
state.error = payload;
})
.addCase(signIn.fulfilled, (state, { payload }) => {
state.loading = false;
state.userInfo = payload;
state.userToken = payload.userToken;
});
},
});
因为我没有指定任何类型的操作,所以当我尝试将 action.payload 分配给 state.userInfo 时会显示一条错误消息,但我不知道该怎么做。请帮助我。
我四处寻找但没有找到答案
您不需要提供该类型 - 它将从您传入的
createAsyncThunk
实例中推断出来 - 在 signUp
到 string | null
的情况下。
也许您没有正确输入
signIn
?