0

I am using redux promise middleware. I am trying to pass the value in Propsx to state. Props comes empty in useEffect. How can I transfer the contents of the props to state. Props value comes next.

action:

export function fetchBasket() {
  return dispatch => {
    dispatch({
      type: 'GET_BASKET',
      payload: axios.get('url', {
      })
        .then(response => response.data)
    });
  };
}

reducer:

const initialState = {
  fetching: false,
  error: {},
  basket: []
};

export default (state = initialState, { type, payload }) => {
  switch (type) {

  case types.GET_BASKET_PENDING:
    return {
      fetching: true
    };

  case types.GET_BASKET_FULFILLED:
    return { 
      ...state,
      fetching: false,
      basket: payload.result,
    };

  case types.GET_BASKET_REJECTED:
    return { 
      fetching: false,
      error: payload.result
    };

  default:
    return state;
  }
};

use in Component

useEffect(() => {
    props.fetchBasket();
    console.log(props.basket); // null :/
  }, []);
4

2 回答 2

0
useEffect(() => {
  props.fetchBasket();
  console.log(props.basket); // null :/
}, []);

您的道具将仅在下一个事件循环周期中更新,要在内部使用反应挂钩数据更新,useEffect您需要useReducer https://reactjs.org/docs/hooks-reference.html#usereducer

于 2020-04-17T18:47:09.393 回答
0

[在此处输入链接描述][1]如果您想在第一次运行(安装)中获得值。fetch here ==> useLayoutEffect这将给出useEffect ()[] 中的值。[uselayouteffect]:https ://reactjs.org/docs/hooks-reference.html#uselayouteffect

于 2020-04-17T18:55:19.743 回答