Javascript Redux一次设置多个状态

Javascript Redux一次设置多个状态,javascript,reactjs,redux,react-redux,react-hooks,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]

我想在星期一、星期二等适当的日子更新状态。基本上,我只是将状态移动到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
Reducer:

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
使用异步操作

更新
getMealofDay
以仅使用一些
day
和offset
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
});
getFounds
转换为异步操作创建者

你的基本模式是这样的

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),
}
但这并不是非常干燥,实际上是等待每一个都完成,甚至在开始下一个之前。我们可以做得更好。将所有异步函数排队到一个数组中并
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;
  }
};


只需按照安装说明将redux thunk中间件添加到redux应用商店。

redux还原程序同步运行,但redux能够使用(或其他)。在async action creator中处理异步逻辑,并将结果值分派到redux存储。如果你不想自己尝试一下,看看什么是有效的或者有什么问题,我可以尝试一下实现。是的,我会非常感激,谢谢,抱歉,这比我预期的时间长了一点。我不使用redux thunk,所以我不是100%相信我的想法会奏效,所以我创建了一个运行的代码沙盒来向自己证明它是可行的。这非常有效!非常感谢您花时间一步一步地解释解决方案。肯定给了我一个更好的关于事情应该如何运作的概述。我很感激,德鲁!你好,Drew,可以在
GetFinds
操作中返回相关值,以便在其他thunk操作中重复使用吗?假设我想做
const someAction=(startDay,other)=>(dispatch,getState)=>GetFounds(startDay)(dispatch,getState)。然后(Founds=>“用餐食做点什么”)
@HMR我想我可以遵循这个代码。Thunks能够将值返回给调用者,也就是说,将表单提交到某个端点时,错误/成功返回到UI。异步操作,如果它们返回一个承诺(我认为大多数会),也是可链接的。异步操作还可以调度其他异步操作。