我的reactjs reduxtoolkit切片不会更新状态

问题描述 投票:0回答:2

好的,所以我需要消息 redux 状态来接收来自 emailChange api 调用的消息。

我对此很陌生,所以请记住这一点。

这是我的身份验证切片操作的函数

export const emailChange = createAsyncThunk(
  "auth/emailChange",
  async ({ email, change }, thunkAPI) => {

      const data = await AuthService.emailChange({email, change})
      thunkAPI.dispatch(setMessage(data.message));
      console.log(data);
      return data; 
    })

认证切片

export const logout = createAsyncThunk("auth/logout", async () => {
  await AuthService.logout();
});

const initialState = user
  ? { isLoggedIn: true, user }
  : { isLoggedIn: false, user: null };

const authSlice = createSlice({
  name: "auth",
  initialState,
  extraReducers: {
    [register.fulfilled]: (state, action) => {
      state.isLoggedIn = false;
    },
    [register.rejected]: (state, action) => {
      state.isLoggedIn = false;
    },
    [login.fulfilled]: (state, action) => {
      state.isLoggedIn = true;
      state.user = action.payload.user;
    },
    [login.rejected]: (state, action) => {
      state.isLoggedIn = false;
      state.user = null;
    },
    [logout.fulfilled]: (state, action) => {
      state.isLoggedIn = false;
      state.user = null;
    },
  },
});

const { reducer } = authSlice;
export default reducer;

我发送电子邮件的位置更改

 const handleSubmit = (formValue) => {
    setSuccessful(false);
    setLoading(true);
    if (change!=="email") {
    dispatch(forgottenPassword(formValue))
    .then((response) => {
        if (response.payload.status === "PENDING"){
            setSuccessful(true);
            //navigate(`/emailsent/${formValue.email}/${true}`) 
        }
            setLoading(false);
            setMessage(response.payload)
        })  
    }else if(change==="email") {
        const {email} = formValue
        const post = {change:true, email}
        dispatch(emailChange(post))
        .then((response) => {
            if (response.payload.status === "PENDING"){
                setSuccessful(true);
            } 
                setLoading(false);
                setMessage(response.payload)
                console.log(message2) //this is the message redux state
            }) 
    }       
};

API调用

const emailChange = ({email, change}) => {
  return api
    .post("/auth/emailChange", {email, change})
    .then((response) => {
      return response.data;
    });
};

消息切片

import { createSlice } from "@reduxjs/toolkit";

const initialState = {};

const messageSlice = createSlice({
  name: "message",
  initialState,
  reducers: {
    setMessage: (state, action) => {
      return { message: action.payload };
    },
    clearMessage: () => {
      return { message: "" };
    },
  },
});

const { reducer, actions } = messageSlice;

export const { setMessage, clearMessage } = actions
export default reducer;

为什么这段代码不起作用?

我尝试并检查了许多不同的配置。

控制台日志显示正确的有效负载正在发送到消息,但状态未更新

除了消息状态未根据控制台日志更新外,一切都正常进行。

我希望这段代码中的内容是显而易见的

我的身份验证切片操作中的此功能运行良好

export const register = createAsyncThunk(
  "auth/register",
  async ({ username, email, password }, thunkAPI) => {
    try {
      const response = await AuthService.register(username, email, password);
      thunkAPI.dispatch(setMessage(response.data.message));
      return response.data;
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();
      thunkAPI.dispatch(setMessage(message));
      return thunkAPI.rejectWithValue();
    }
  }
);
reactjs redux-toolkit redux-thunk
2个回答
1
投票

好吧,处理这个问题的更好方法实际上是在 extraReducers 中。请注意,我个人使用“地图对象”表示法,但您也可以使用构建器。 这里是 extraReducers 的文档。

** 请注意,定义初始状态是一个好主意。 此外,您很可能“不会”收到更新,因为您要返回。相反,你应该在你的reducers中分配状态,即在setMessage中你应该在redux工具包中执行这个state.message = action.payload,它在幕后使用immer,这样你就可以改变状态,它将在场景后面处理它。 import { createSlice } from "@reduxjs/toolkit"; export const emailChange = createAsyncThunk( "auth/emailChange", async ({ email, change }, thunkAPI) => { const data = await AuthService.emailChange({email, change}) // No need to dispatch the thunkAPI as it will automatically look in the extra reducers. return data; }) const initialState = { message: "" }; const messageSlice = createSlice({ name: "message", initialState, reducers: { setMessage: (state, action) => { state.message = action.payload; }, clearMessage: () => { state.message = ""; }, }, extraReducers: { [emailChange.pending]: (state, action) => { // Great place to set isLoading true. }, [emailChange.fullfilled]: (state, action) => { // Heads up its atleast action.payload might want to check in debugger if you need to dig further into the object. state.message = action.payload; // Great place to set the isLoading false. }, [emailChange.rejected]: (state, action) => { // Great place to set an error message to display to user or whatever. // Might set isLoading to false here. }, [register.fulfilled]: (state, action) => { // Could add a string here or back in the createAsyncThunk on the return you could destructure and add a message there then do action.payload.message or whatever. state.message = "Login successful"; }, } }); const { reducer, actions } = messageSlice; export const { setMessage, clearMessage } = actions export default reducer;



0
投票
{message2} = useSelector((state) => state.message.message); 到 message2 = useSelector((state) => state.message.message);


允许它工作。

我还将 emailchange 操作放在自己的切片中,它似乎有帮助,但不确定。

© www.soinside.com 2019 - 2024. All rights reserved.