reducer 中的 Redux 状态不是最新的?

Redux state in reducer not up to date?

我正在使用 React/Redux 构建一个应用程序,我有一组异步加载到 Redux 状态的产品,然后我想从中提取单个产品。但是,我为此编写的减速器无法正常工作,因为它正在将状态注册为 null。这让我感到困惑,因为在返回操作之前在 thunk 操作创建者中调用 getState() 并触发 reducer 正在使用产品数组记录正确的状态。

这是我的代码中的错误还是 redux 状态更新方式的一部分?

动作创作者:getSingleProduct

export const getSingleProduct = productName => (dispatch, getState) => {
  const action = { type: 'GET_SINGLE_PRODUCT', productName };
  if (!getState().products.length) return dispatch(getAllProducts())
    .then(() => {
      console.log('STATE IN ACTION CREATOR THEN BLOCK', getState());
      return dispatch(action);
    })
    .catch(console.log);
  else return action;
}

减速机:currentProduct

const currentProduct = (state = null, action) => {
switch (action.type) {
    case 'GET_SINGLE_PRODUCT':
      console.log('STATE IN REDUCER', state);
      return state.products.filter(prod => prod.name.toLowerCase() === action.productName)[0];
      break;
    default:
      return state;
  }
}

控制台日志输出

STATE IN ACTION CREATOR THEN BLOCK 
{ basket: Array(0), products: Array(6), currentProduct: null }


STATE IN REDUCER
null

状态为空,因为您在第一次函数调用时将其定义为空。 console.log 操作完成后的状态,您会看到值 运行。 return修改状态是错误的。应该return新状态。

const currentProduct = (state = null, action) => {
 switch (action.type) {
  case 'GET_SINGLE_PRODUCT':
    console.log('STATE IN REDUCER', state);
    const products = state.products.slice().filter(prod => prod.name.toLowerCase() === action.productName)[0];

    return { ...state, products } 
    break;
  default:
   return state;
 }
}

Reducer 状态实际上是最新的,问题是对 reducer 状态如何工作的误解。我试图利用从减速器的 state 参数中不可用的依赖状态。我的解决方案是将此信息从依赖状态传递到操作对象上。

动作

export const getSingleProduct = (productName, products = []) => (dispatch, getState) => {
  let action = {
    type: 'GET_SINGLE_PRODUCT',
    productName,
    products: getState().products
  }
  if (!action.products.length) dispatch(getAllProducts())
    .then(() => {
      action = Object.assign({}, action, { products: getState().products });
      dispatch(action);
    })
    .catch(console.log);
  else return action;
}

减速机

const currentProduct = (state = {}, action) => {
  switch (action.type) {
    case 'GET_SINGLE_PRODUCT':
      const currentProduct = action.products.filter(prod => prod.name.toLowerCase() === action.productName)[0];
      return Object.assign({}, state, currentProduct);
    default:
      return state;
  }
}