在react / redux

时间:2017-02-06 20:29:10

标签: reactjs onclick redux state rerender

我有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绑定到该状态。我知道如何解决这个问题,我是一个相当新的反应/减少 - 它是我在lib中的第一个侧面项目。

谢谢

更新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);

1 个答案:

答案 0 :(得分: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