无法从连接的 React 组件触发 createAsyncThunk

Posted

技术标签:

【中文标题】无法从连接的 React 组件触发 createAsyncThunk【英文标题】:Can't get createAsyncThunk to fire from connected React Component 【发布时间】:2020-10-30 14:19:58 【问题描述】:

我正在尝试使用 createAsyncThunk 进行一些 API 调用,但我似乎无法让它工作。我的正常操作正在工作,所以我必须正确地将我的组件连接到 redux,但是我缺少关于 createAsyncThunk 的一些不同的东西。从下面调用 this.props.checkSession() 什么都不做。 checkSession 中的任何 console.logs 都不会打印,而 fetch() 永远不会到达服务器。

应用屏幕

import React from 'react';
import  View, Text, ActivityIndicator  from 'react-native';
import  connect  from 'react-redux';
import  checkSession  from './actions';
import  setToken  from './reducer';

class AppScreen extends React.Component 
  constructor(props) 
    super(props);
  

  componentDidMount() 
    console.log("Mounted")
    this.props.checkSession();
    console.log("Moving on")
    if (!this.props.loading && !this.props.auth_token) 
      this.props.navigation.navigate('Auth')
    
  

  render() 
    if (this.props.loading) 
      return (
        <View style= flex: 1 >
          <ActivityIndicator />
        </View>
      )
     else 
      return (
        <View>
          <Text>You're in! this.props.auth_token</Text>
        </View>
      )
    
  


function mapStateToProps(state) 
  return 
    user: state.app.user,
    auth_token: state.app.auth_token,
    loading: state.app.loading,
    error: state.app.error
  ;


const mapDispatchToProps = dispatch => 
  return 
    checkSession: () => dispatch(checkSession),
    setToken: token => dispatch(setToken(token))
  


export default connect(mapStateToProps, mapDispatchToProps)(AppScreen);

动作

import  createAsyncThunk  from "@reduxjs/toolkit";
import  API_URL, ENDPOINTS  from "./../constants";

export const checkSession = createAsyncThunk("checkSession", (thunkAPI) => 
  console.log("Running")
  let body = 
    method: 'POST',
    headers: 
      Accept: 'application/json',
      'Content-Type': 'application/json',
    ,
    body: JSON.stringify(auth_token: thunkAPI.getState().app.auth_token)
  

  console.log("Checking session.")

  return fetch(`$API_URL$ENDPOINTS.CHECK_SESSION`, body)
    .then(response => 
      console.log(`API hit: $response.ok`)
      if (!response.ok) throw Error(response.statusText);
      return response.json();
    )
    .then(json => json);
);

减速器

import  createSlice  from "@reduxjs/toolkit";

import  checkSession  from "./actions"

const appSlice = createSlice(
  name: "app",
  initialState: 
    loading: true,
    auth_token: "",
    error: "",
    user: 
  ,
  reducers: 
    setToken: (state, action) => 
      state.auth_token = action.payload;
      state.loading = false;
    ,
  ,
  extraReducers: 
    [checkSession.pending]: state => 
      state.loading = true;
    ,
    [checkSession.rejected]: (state, action) => 
      state.loading = false;
      state.error = action.error.message;
    ,
    [checkSession.fulfilled]: (state, action) => 
      state.loading = false;
      state.user = action.payload.user;
      state.auth_token = action.payload.auth_token;
    
  
);

export const  setToken  = appSlice.actions;
export const appReducer = appSlice.reducer;

商店

import  appReducer  from "./App/reducer";
import  authReducer  from "./Auth/reducer";
import  configureStore, getDefaultMiddleware  from "@reduxjs/toolkit";

const middleware = [
  ...getDefaultMiddleware(),
]

const store = configureStore(
  reducer: 
    app: appReducer,
    auth: authReducer
  ,
  middleware,
);

export default store;

【问题讨论】:

【参考方案1】:

您使用 checkSession 错误。应该是dispatch(checkSession())

也就是说,你也应该使用the "object shorthand" form of mapDispatch,像这样:

const mapDispatch = checkSession, setToken;

【讨论】:

以上是关于无法从连接的 React 组件触发 createAsyncThunk的主要内容,如果未能解决你的问题,请参考以下文章

从 React 中的远程组件触发一个组件中的 CSS 动画

如何从另一个 React / ReactNative 组件触发 GraphQL 查询

无法通过 React 和 Redux 将相同的表单组件用于添加或编辑模式

无法在 react native 中使用 redux 连接多个组件

如何使用 react-testing-library 在 react-select 组件上触发更改事件?

我的 Redux 状态发生了变化,为啥 React 没有触发重新渲染?