Redux State计数返回

时间:2017-09-27 07:08:22

标签: reactjs redux

我正在尝试在我的React应用程序中构建一个功能,显示特定帖子的数量评论。由于我没有来自后端的这些信息,所以尝试在返回的状态下设置.length

然而,似乎我已经以错误的方式构建了减速器,但我不确定它是什么问题。现在我刚收到undefined。

建立如下

动作

    export function getPostComments(id) {
    const request = API.fetchPostComments(id)

    return (dispatch) => {
        request.then(({data}) => {
            dispatch({type: COMMENTS_GET_POSTCOMMENTS, payload: data})
        });
    };
}

减速

export default function(state = {}, action) {
  switch (action.type){
        case COMMENTS_GET_POSTCOMMENTS:
      return {...state, ...action.payload}

组件

componentWillMount() {
        this.props.getPostComments(this.props.id);
    }

....

<span>{`comments ${this.props.comments.length}`}</span>

....


function mapStateToProps(state) {
    return {
        comments: state.comments,

    }
}


export default connect(mapStateToProps, {postPostVote, getPostComments})(PostComponent);

修改

如果我将减速器更改为return action.payload,我将从服务器检索信息。我将首先收到2的注释号,但是由于列表中的最后一个帖子没有,因此将其替换为0有任何意见。所以我在这里覆盖?而且大多数都是错的

回购:https://github.com/petterostergren/readable

现在谢谢!

1 个答案:

答案 0 :(得分:0)

export function getAllCategories() {
 return (dispatch) => {
    API.fetchAllCategories()
     .then(data => {
        dispatch({type: CATEGORIES_GET_ALL_CATEGORIES, payload: data})
     });
 };
}

对您的API fetchAllCategories的调用是异步的,您之前所做的是您调用API而不是等待它的响应。这就是你在有效载荷中传递undefined的原因。

所以你需要做的是使用另一个承诺获取调用的链。

我在我的应用程序中使用redux-thunk,这就是我使用它的方式。请参阅下面的代码。

export function loadPayments () {
   return dispatch => PaymentsAPI.getCustomerPaymentMethods()
                  .then((paymentMethods) => { 
                    dispatch({
                      type: actionTypes.LOAD_PAYMENTS_SUCCESS,
                      payments: paymentMethods
                    }) 
                  })
                  .catch((error) => {
                    console.log('Error', error);
                  })
 }

对于API调用我正在使用Fetch&amp;爱可信。你可以使用任何你想要的。两者都很好。

要更新您的reducer,以便它添加以前的值,请执行以下操作

case actionTypes.LOAD_SAVED_CARDS_SUCCESS: {
  return { 
    ...state, 
    payments: [ ...state.payments, ...action.payments],
    totalpayments: state.payments.length + action.payments.length
  };
}

减压器在这里会做的是,它会附加你所有的假设支付方法i,以前的方法+新方法以及计数更新。