Redux一次设置多个状态

时间:2020-09-11 06:54:28

标签: javascript reactjs redux react-redux react-hooks

我想根据情况在星期一,星期二等更新状态。基本上,我只是将状态移动到redux存储,我有两个函数想转换为redux状态,但是由于使用React-hooks很难,并且转换为redux状态也很困难。请你能帮助我。

这是我要转换为Redux的两个React函数:

const Restaurant = () => {
  // trying to convert this state to redux store state
  const [Monday, setmonday] =useState([])
  const [Tuesday,settuesday] =useState([])
  const [Wednesday,setwednesday] =useState([])
  const [Thursday, setthursday] =useState([])
  const [Friday, setfriday] =useState([])
  const [Saturday, setsaturday] =useState([])
  const [Sunday, setsunday] =useState([])

  // trying to put this function in my reducer and how it will work with its async alternative
  const getMeals = async (Monday, callback) => {
    try {
      await getMealofDay(Monday, setmonday, 0)
      await getMealofDay(Monday, settuesday, 1)
      await getMealofDay(Monday, setwednesday, 2)
      await getMealofDay(Monday, setthursday, 3)
      await getMealofDay(Monday, setfriday, 4)
      await getMealofDay(Monday, setsaturday, 5)
      await getMealofDay(Monday, setsunday, 6)
    }
    catch{
      console.log("error")
    }
    if (callback) {
      callback()

    }
  }

  const getMealofDay = async (Monday, setDay, i) => {
    try {
      let day = new Date(Monday);
      day.setDate(Monday.getDate() + i);
      let mealId = `${day.getDate()} ${months[day.getMonth() + 1]} ${day.getFullYear()}`
      let meal = await AsyncStorage.getItem(`${mealId}`);
      await setDay(JSON.parse(meal))

    } catch{ }

  }
}

这是我的Redux减速器:

import { CREATE_DAY } from '../actions/day'
const initialState = {
    //Days of the week
    Monday: [],
    Tuesday: [],
    Wednesday: [],
    Thursday: [],
    Friday: [],
    Saturday: [],
    Sunday: [],
}
const PlanReducer = (state=initialState, action) =>{
    switch(action.type){
        case CREATE_DAY:
            return
        default: 
            return state
    }
}
export default PlanReducer

1 个答案:

答案 0 :(得分:2)

使用异步操作

async actions

更新getMealofDay以使用 some day并仅偏移i,并返回已解析的JSON膳食对象。

const getMealofDay = async (monday, i) => {
  try {
    const day = new Date(monday);
    day.setDate(monday.getDate() + i);

    const mealId = `${day.getDate()} ${months[day.getMonth() + 1]} ${day.getFullYear()}`;
    const meal = await AsyncStorage.getItem(`${mealId}`);

    return JSON.parse(meal);
  } catch {}
};

创建特定日期的成功操作类型和创建者

export const CREATE_DAY = "CREATE_DAY";
export const mealDaysSuccess = (days) => ({
  type: CREATE_DAY,
  days
});

getMeals转换为异步操作创建者。

您拥有的基本模式是

const days = {
  Monday: await getMealofDay(monday, 0),
  Tuesday: await getMealofDay(monday, 1),
  Wednesday: await getMealofDay(monday, 2),
  Thursday: await getMealofDay(monday, 3),
  Friday: await getMealofDay(monday, 4),
  Saturday: await getMealofDay(monday, 5),
  Sunday: await getMealofDay(monday, 6),
}

但这不是 DRY ,它实际上等待每个完成,甚至不启动下一个。我们可以做得更好。将所有异步函数放入数组并Promise.all

export const getMeals = (startDay) => async (dispatch) => {
  const dayPromises = [0, 1, 2, 3, 4, 5, 6].map((offset) =>
    getMealofDay(startDay, offset)
  );

  const [
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
  ] = await Promise.all(dayPromises);
  const days = {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
  };

  dispatch(mealDaysSuccess(days));
};

在减速机中,从操作中访问日餐

const initialState = {
  //Days of the week
  Monday: [],
  Tuesday: [],
  Wednesday: [],
  Thursday: [],
  Friday: [],
  Saturday: [],
  Sunday: []
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case CREATE_DAY:
      return { ...action.days };

    default:
      return state;
  }
};

Edit redux-set-multiple-states-at-once

只需按照设置说明将redux-thunk中间件添加到您的redux存储中即可。