我正在尝试对一些API调用使用createAsyncThunk,但似乎无法正常工作。我的常规操作正常,因此我必须将组件正确连接到Redux,但是缺少的createAsyncThunk有所不同。从下面调用this.props.checkSession()不会执行任何操作。 checkSession内的console.logs都不会被打印,而fetch()永远不会命中服务器。
AppScreen
pathos
动作
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;
答案 0 :(得分:2)
您使用的checkSession
错误。应该是dispatch(checkSession())
。
也就是说,您也应该像这样使用the "object shorthand" form of mapDispatch
:
const mapDispatch = {checkSession, setToken};