首页 > 解决方案 > TypeError:在使用 createAsyncThunk 和 createSlice 时无法读取 redux 工具包中未定义的属性“待定”(@reduxjs/toolkit”:“^1.4.0)

问题描述

我在将extraReducer添加到我的 createSlice时遇到了上述错误

这是一个反应原生的应用程序

这是我的代码:

    export const login = createAsyncThunk(
      'loginAuth/login',
      async ({username, password}) => {
        try {
          const res = await api.post('SomeApi', {
            username,
            password,
          });
         
          return res.data;
        } catch (e) {
          return console.error(e.message);
        }
      },
    );

    const loginSlice = createSlice({
      name: 'loginAuth',
      initialState: {
        loginStatus: false,
        isLoading: false,
        error: '',
      },
      reducers: {
        //Yet to be filled
      },
      extraReducers: {
        [login.pending]: (state) => {
          state.isLoading = true;
        },
        [login.fulfilled]: (state, action) => {
          state.isLoading = false;
        },
        [login.rejected]: (state, action) => {
          state.error = action;
        },
      },
    });

这是我来自另一个文件的调度代码:

    class Login extends Component {
      state = {
        data: {
          username: '',
          password: '',
        },
        textHidden: true,
      };
    
      handelSubmit = (status) => {
        if (status) {
          this.props.login(this.state.data);
        }
      };
    render(){
        return(
    //The UI for Input is here. I confirmed that the dispatch is working fine. I did log the username and password. But I didn't use the createAsyncThunk
    )
    }
    
    const mapDispatchToProps = (dispatch) => ({
      login: (data) => dispatch(login(data)),
    });
    
    export default connect(null, mapDispatchToProps)(Login);

为了确认调度,我确实编写了另一个同名的函数 login() 我在其中记录了用户名和密码:

    export const login = ({username, password}) => async (dispatch) => {
      console.log(username,password); // Here the dispatch is working fine
      //  called that API and dispatched to a reducer dispatch(loginSucess(result.data))
        };

使用上面提到的函数,我确实调用了 API 并检查了是否成功。它工作得很好。我必须编写一个 reducerloginSucess 来交叉检查 API 是否正常工作。它确实工作正常

我不明白我哪里错了!!

需要帮忙!!

这是错误的屏幕截图:

在此处输入图像描述

标签: react-nativeredux-thunkredux-toolkit

解决方案


我得到了答案。你在这里检查同样的。这是我的愚蠢。我没有正确安排代码。login应该在上面loginSlice。谢谢!!


推荐阅读