因此,在编写了一个完整的 Web 应用程序后,使用 react 和 props-drilling 像你以前从未见过的那样深入,你不应该这样做,我决定试一试 react 'contexts'。我阅读了 React 文档,并决定将我的状态(它们非常需要帮助,因为它们深深 Root 于组件之后的组件中)放在一个单独的文件中:
-创建一个'context.js'文件
-在里面我会有:[注意我里面有两个状态]
import { createContext } from 'react'
export const context = createContext();
export default function ContextProvider (props) {
const [state1, setState1] = useState();
const [state2, setState2] = useState();
return (
<context.provider value={[state1, setState1, state2, setState2]}>
props.children
</context.provider>
)
}
//inside a functional component
...
const [state1, setState1] = useContext(context); //assuming I only need state1 in this component
...
现在我的问题是这种方法的效率如何。在一些博客中,我读到了使用带有钩子(Hook)的上下文,我读到的每个博客都使用了“useReduce”钩子(Hook)。有人可以解释为什么使用“useReduce”,它解决了什么问题以及如何解决。这将不胜感激。
最佳答案
这根本没有效率:任何时候你调用setState1()
它将导致重新渲染 <ContextProvider>
,因此整个应用程序,大概是包装到 <ContextProvider>
.
考虑使用上下文检查我的库中的全局状态管理:https://www.npmjs.com/package/@dr.pogodin/react-global-state :)
关于javascript - 为什么在实现全局作用域状态时我会在 react 中使用 'useReduce'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67270914/