0

我有 post 方法助手,我正在对基本上正在运行的服务器进行其余调用,但视图/容器在调用后没有重新呈现。

export function postData(action, errorType, isAuthReq, url, dispatch, data) {
  const requestUrl = API_URL + url;
  let headers = {};

  if (isAuthReq) {
    headers = {headers: {'Authorization': cookie.load('token')}};
  }

  axios.post(requestUrl, data, headers)
    .then((response) => {
      dispatch({
        type: action,
        payload: response.data
      });
    })
    .catch((error) => {
      errorHandler(dispatch, error.response, errorType)
    });
}

我收到以下错误:dispatch is not defined在我调用此方法时在浏览器中

我从容器中调用如下:

handleFavorite(buildingId) {
  const url = `/building/${buildingId}/toogle-favorite`;
  postData(FETCH_All_BUILDING, AUTH_ERROR, true, url, this.props.dispatch, {});
}

这就是我的连接方法的样子:

function mapStateToProps(state) {
  return {
    buildings: state.building.buildings,
    error: state.building.error,
    userId: state.auth.userId
  }
}

export default connect(mapStateToProps, {buildingsAll})(BuildingAll);

我的问题是...

如何重新渲染我的视图?我想给该方法的这个调度不可用。是否有可能将休息与状态绑定mapDispatchToProps。知道如何解决这个问题,我对 react/redux 还很陌生——这是我在那个库中的第一个副项目。

谢谢

更新 1

我已经更新了代码,但出现了下一个错误,并且我的视图现在没有呈现(没有显示)。

mapDispatchToProps() in Connect(BuildingAll) must return a plain object. Instead received function 
bundle.js:26 Uncaught TypeError: finalMergeProps is not a function

const mapDispatchToProps = (dispatch) => bindActionCreators(postDataThunk, dispatch);

export default connect(mapStateToProps, mapDispatchToProps, {buildingsAll})(BuildungAll);
4

1 回答 1

1

您需要在容器中绑定动作创建者

const { bindActionCreators } = require("redux");

const mapStateToProps = (state) => {
    return {
        buildings: state.building.buildings,
        error: state.building.error,
        userId: state.auth.userId
    }
}
const mapDispatchToProps = (dispatch) => bindActionCreators(YourActions, dispatch);

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

然后你的动作变成这样:

import thunk from 'redux-thunk';
const postData = (action, errorType, isAuthReq, url, data) => {
    return (dispatch) => {
        const requestUrl = API_URL + url;
        let headers = {};

        if (isAuthReq) {
            headers = { headers: { 'Authorization': cookie.load('token') } };
        }

        axios.post(requestUrl, data, headers)
            .then((response) => {
                dispatch({
                    type: action,
                    payload: response.data
                });
            })
            .catch((error) => {
                errorHandler(dispatch, error.response, errorType)
            });
    };
};

因为你的 postData 可能有一些副作用,因为它异步获取一些东西,所以你需要一个 thunk

阅读这篇文章:http ://redux.js.org/docs/advanced/AsyncActions.html

于 2017-02-06T21:14:44.073 回答