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

Can't get createAsyncThunk to fire from connected React Component

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

AppScreen

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;

您使用的 checkSession 有误。应该是 dispatch(checkSession()).

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

const mapDispatch = {checkSession, setToken};