Redux开发工具中会收到Redux道具,但React组件中不会

时间:2019-07-18 21:25:22

标签: javascript reactjs redux react-redux

我正在将Redux道具传递到从获取有效载荷获取的组件。有效负载成功更改了我的reducer中的状态,并且根据我的Redux DevTools,当我成功进行操作时,我正在尝试将状态传递给组件的组件成功地获得了prop(动作中获取的对象数组)。记录道具或尝试执行任何操作,它会显示为空数组。

我的索引减少器:

export default combineReducers({
  cart: cartitemReducer,
  products: productReducer,
})

提取操作:

export const fetchCart = () => dispatch => {
  fetch('http://localhost:3000/api/v1/cartitems/')
    .then(res => res.json())
    .then(cartjson =>
      dispatch({
        type: 'FETCH_CART',
        payload: cartjson
    }))
}

减速器:

const initialState = {
  userCart: [],
  cartItem: {}
}

export default function(state = initialState, action) {
  switch(action.type) {
    case FETCH_CART:
      return {
        ...state,
        userCart: action.payload
      };

将状态映射到道具:

const mapStateToProps = state => ({
  cart: state.cart.userCart
})

当我console.log(this.props.cart)时,它返回一个空数组。但是我的DevTools正确显示了cart.userCart下的数组内容

1 个答案:

答案 0 :(得分:0)

这完全取决于您console.log()的位置。如果您在componentDidMount()中运行它,那么您将得到一个空数组,因为console.log()在完成提取请求和更新化简器之前运行。 componentDidMount()将不会再次触发。

但是,您的代码看起来可以正确设置。您应该能够在componentDidUpdate()中打印结果,只要您获得更新的道具或状态便会触发该结果。

componentDidUpdate(prevProps){
  if(prevProps.cart.length !== this.props.cart.length){
    console.log(this.props.cart)
 }
}
相关问题