首页 > 解决方案 > 动作必须是普通对象。使用自定义中间件进行异步操作。React、Redux、Thunk

问题描述

请帮忙,这在过去的四天里一直困扰着我,我无法解决。

我正在使用 react 和 redux 来提取一些数据,这些数据来自我知道我已经安装了 thunk 但我不知道如何使用它。但是我的动作又回来了:动作必须是普通对象。使用自定义中间件进行异步操作。

行动:

export const getShifts = () => dispatch => {
console.log('Fetching list of shifts for user...');
const request = API.get("StaffAPI", "/shifts", {
    headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json',
    }
})
.then(response =>
    dispatch({type: 'SHIFTS_LOAD_SUCCESS', response})
)
.catch(err =>
    dispatch({type: 'SHIFTS_LOAD_FAIL'})
)
}

减速器:

import _ from "lodash"
import { getShifts} from '../actions';

export default function(state = {}, action) {
switch(action.type){
 case SHIFTS_LOAD_SUCCESS:
    return { ...state, rota: action.response };
  }
 }

零件:

 componentWillMount() {
  this.props.getShifts();
  }
  renderPosts(){

console.log(this.props);
 return (

<div>
 <button onClick={this.logOut}>LogOut</button>
  <h4>hello{this.props.rotaData}</h4>
</div>
);


}


render() {
  return (
  <div className="row">
  {this.renderPosts()}

  </div>
);
}
}

function mapStateToProps(state){
 return{ rota: state.response };
}

 export default connect(mapStateToProps, {getShifts: getShifts}) (StaffRota);

我对这一切都很陌生,如果它很简单,请原谅我。Know-one else 已经能够解决我的问题。

标签: javascriptreactjsredux

解决方案


redux-thunk在创建商店时进行了设置吗?它应该是这样的

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Create store
const store = createStore(yourReducers, applyMiddleware(thunk));

尝试仔细检查 thunk 文档https://github.com/reduxjs/redux-thunk


推荐阅读