简体   繁体   English

在反应中使用过多的 useState 钩子。 我该如何重构这个?

[英]Using too many useState hooks in react. How do I refactor this?

the useState hooks are great. useState 钩子很棒。 I mainly use the useState hooks to initialise certain states, and I also pass the function to children components to change the states.我主要使用 useState 钩子来初始化某些状态,我还将 function 传递给子组件以更改状态。 However, I realise I am starting to use too many useState hooks in my parent page component.但是,我意识到我开始在我的父页面组件中使用太多的 useState 挂钩 This looks and feels wrong, because I am starting to have about 6-10 useState hooks in the parent page component.这看起来和感觉都是错误的,因为我开始在父页面组件中有大约 6-10 个 useState 挂钩
Without showing the code, Is there a better way to do this?在不显示代码的情况下,有没有更好的方法来做到这一点? Maybe a better practice, or a better way to refactor.也许是更好的实践,或者更好的重构方式。
Thanks谢谢

Whenever you encounter a problem like this you should first look if you can split your component into multiple smaller ones.每当您遇到这样的问题时,您应该首先查看是否可以将组件拆分为多个较小的组件。 However there are scenarios where that's not an option.但是,在某些情况下,这不是一种选择。 In those cases I would advice using useReducer.在这些情况下,我建议使用 useReducer。

// before

const {cache, setCache } = useState({});
const {posts, setPosts } = useState({});
const {loading, setLoading } = useState(false);

// Would become after refactor

const initialState = {
  cache: {},
  posts:{},
  loading: false
}

const [state, dispatch] = useReducer(reducer, initialState);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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