简体   繁体   中英

How to avoid React Hooks inside loops and conditions?

Hey I have the following problem ! I am using an Use Effect Hook to update my taskList when I open my WebApp. So I have to lists a list with task which has the attribute recuring tasks (recuringTaskManager.lastWeeklyReset) and a list wich can have attributes with recuring and without (taskList). So my goal is to update taskList with the other one when a special condition accure (if differenceInDays....). so I want to delete some tasks in Taskslist therefore the filter function and add them again so that a special attribute can get refreshed. I found out that using hooks in conditions and loops is always bad but I don't know how I could code it without loops and conditions.

Maybe you know :)

useEffect(() => {
    if (!isInitialized) return
    if (differenceInDays(new Date("July 28, 2022 00:00:00"), state.recuringTaskManager.lastWeeklyReset) >= 7) {
      for (let task of state.recuringTaskManager.recuringTaskListWeekly) {
        const {id} = task
        setState({...state, taskList: state.taskList.filter((task: Task) => task.id !== id)})
state.recuringTaskManager.recuringTaskListWeekly)
      }

      setState({...state, taskList: [...state.recuringTaskManager.recuringTaskListWeekly, ...state.taskList]})
    }
  }, [isInitialized]) ``` 

What you can do to avoid that is to set a variable and increment it in the loop and then set the state outside the loop or I think for your case you can just do this in one line

setState({...state, taskList: state.taskList.filter(({id}) => !state.recuringTaskManager.recuringTaskListWeekly.some(({id: id2}) => id === id2))})

The some method return true if one of the item of the array met the condition, if not it returns false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM