Redux Thunk 不起作用 - 操作应该是使用自定义中间件的对象



有人能帮我找出我做错了什么吗?我一直在获取应该是对象使用自定义中间件错误的操作。如果我试图在fetchAdmins()上返回类似{type:‘SOMETHING’}的函数,这是有效的,但根据redux thunk文档,我应该能够返回一个以dispatch为params的函数,我就是这么做的,但可能我错过了什么。

store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import allReducers from './js/reducers/index.js';
const Store = (initialState) =>
createStore(
allReducers,
initialState,
applyMiddleware(thunk)
);
export default Store;

RootAdmin.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Route } from 'react-router-dom';
import { fetchAdmins, addAdmin, deleteAdmin } from '../actions/actions.js';
@connect(
state => ({
admins: state.admins
}),
dispatch => bindActionCreators({
fetchAdmins: fetchAdmins,
addAdmin: addAdmin,
deleteAdmin: deleteAdmin
}, dispatch)
)
class RootAdmin extends Component {
// ...codes
componentDidMount() {
this.props.fetchAdmins();
}
// ...codes
}
};
export default RootAdmin;

actions.js

import axios from 'axios';
export function fetchAdmins() {
console.log('fired'); // this gets fired.
return (dispatch) => {
console.log('not fired'); // not fired.
dispatch({ type: 'FETCHING_ADMINS' });
console.log('fetching'); // won't even log
axios({
url: '/api/fetchAdmins'
})
.then(res => 
dispatch({ type: 'FETCHED_ADMINS', payload: res.data })
)
.catch(err => 
dispatch({ type: 'FAILED_FETCH_ADMINS' })
);
};
}

reducer-admins.js

export default function (state = null, action) {
const { payload } = action;
let newState = {...state};
switch (action.type) {
case 'FETCHING_ADMINS':
newState = {...payload};
newState.log += 'nfetching admins';
console.log('fetching admins');
return newState;
break;
}
return state;
}

非常感谢!

问题不是由您的操作创建者引起的。。。我认为问题在于您的地图DispatchToProps

@connect(
state => ({
admins: state.admins
}),
dispatch => bindActionCreators({
fetchAdmins: fetchAdmins,
addAdmin: addAdmin,
deleteAdmin: deleteAdmin
}, dispatch)
)

请注意,您从状态映射函数返回一个对象,但在调度中,您返回的是bindActionCreators的结果,它可以是一个对象或函数。。。

@connect(
state => ({
admins: state.admins
}),
dispatch => ({
actions: bindActionCreators(Object.assign({}, fetchAdmins, addAdmin, deleteAdmin), dispatch)
})
)

然后访问您的方法如下.props.actions.fetchAdmins();

最新更新