Javascript 具有多个性能值的React上下文API
我正在使用React上下文API来存储10左右的许多全局状态值,可能需要更多的值,许多组件正在使用它们。不幸的是,每当任何值发生更改时,使用useContext钩子的所有组件都必须重新加载。我目前的解决方案是对组件的返回值使用useMemo,对任何复杂函数和自定义挂钩内部使用useCallback。这解决了我大部分的性能问题,但是必须一直使用useMemo和useCallback是非常烦人的,而且很容易丢失一个。有没有更专业的方法 下面是一个基于我的代码的示例: GlobalStateContext.jsJavascript 具有多个性能值的React上下文API,javascript,reactjs,performance,Javascript,Reactjs,Performance,我正在使用React上下文API来存储10左右的许多全局状态值,可能需要更多的值,许多组件正在使用它们。不幸的是,每当任何值发生更改时,使用useContext钩子的所有组件都必须重新加载。我目前的解决方案是对组件的返回值使用useMemo,对任何复杂函数和自定义挂钩内部使用useCallback。这解决了我大部分的性能问题,但是必须一直使用useMemo和useCallback是非常烦人的,而且很容易丢失一个。有没有更专业的方法 下面是一个基于我的代码的示例: GlobalStateConte
import React, { useState } from 'react'
const GlobalStateContext = React.createContext({ })
export const GlobalStateProvider = ({ children }) => {
const [config, setConfig] = useState({
projectInfo: ''
})
const [projectFile, setProjectFile] = useState('./test.cpp')
const [executionState, setExecutionState] = useState("NoProject")
return (
<GlobalStateContext.Provider
value={{
executionState,
config,
projectFile,
setExecutionState,
setConfig,
setProjectFile,
}}
>
{children}
</GlobalStateContext.Provider>
)
}
export default GlobalStateContext
Example.jsx
import React, { useContext } from 'react'
import GlobalStateContext from '../utils/GlobalStateContext.js'
export default Example = () => {
const {
executionState,
setExecutionState,
} = useContext(GlobalStateContext)
return useMemo(
() => (
<div>
The current execution state is: {executionState}
<br />
<button onClick={() => setExecutionState('Running')}>Running</button>
<button onClick={() => setExecutionState('Stopped')}>Stopped</button>
<button onClick={() => setExecutionState('Crashed')}>Crashed</button>
</div>
),
[
executionState,
setExecutionState,
]
)
}
目前,这一问题在上下文中是不可避免的。解决这一问题有一个开放的解决方案,但与此同时,一些解决方案是和Redux,这两种方法都可以防止订阅组件在其读取的数据未更改时渲染。非常感谢您的建议,useContextSelector看起来非常有前途,需要在我的代码中加入的更改比切换到Redux要少。你是最棒的!