Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 不应该';t useContext()是否仅用于低频率更新?(mobx-react-lite)_Reactjs_Mobx React_Mobx React Lite - Fatal编程技术网

Reactjs 不应该';t useContext()是否仅用于低频率更新?(mobx-react-lite)

Reactjs 不应该';t useContext()是否仅用于低频率更新?(mobx-react-lite),reactjs,mobx-react,mobx-react-lite,Reactjs,Mobx React,Mobx React Lite,几乎所有的示例(甚至官方文档)都将mobx react light与useContext()hook结合使用 但是,许多文章和博客建议不要使用useContext()进行中/高频率更新。状态不是可以经常更新的吗 是否应该将包与挂钩结合使用,还是会出现性能问题?useContext()仅用于获取存储值(参考),并且该值不会经常更新,通常您只设置一次存储,之后不触摸它。当您使用操作时,您只会更改存储的可观察值,而不会更改存储本身。所以基本上,Context只用于将引用传递到树下的存储,之后所有的工作

几乎所有的示例(甚至官方文档)都将
mobx react light
useContext()
hook结合使用

但是,许多文章和博客建议不要使用
useContext()
进行中/高频率更新。状态不是可以经常更新的吗

是否应该将包与挂钩结合使用,还是会出现性能问题?

useContext()
仅用于获取存储值(参考),并且该值不会经常更新,通常您只设置一次存储,之后不触摸它。当您使用操作时,您只会更改存储的可观察值,而不会更改存储本身。所以基本上,
Context
只用于将引用传递到树下的存储,之后所有的工作都只由MobX执行

MobX文档中的示例:

import {observer} from 'mobx-react-lite'
import {createContext, useContext} from "react"

const TimerContext = createContext<Timer>()

const TimerView = observer(() => {
    // Grab the timer from the context.
    const timer = useContext(TimerContext) // See the Timer definition above.
    return (
        <span>Seconds passed: {timer.secondsPassed}</span>
    )
})

ReactDOM.render(
    <TimerContext.Provider value={new Timer()}
        <TimerView />
    </TimerContext.Provider>,
    document.body
)
引用文件:

直接使用Observable效果很好,但由于这通常会引入模块状态,因此这种模式可能会使单元测试复杂化。相反,我们建议改用React上下文


更多关于React的最佳实践:

等等,我想我误解了什么。假设我的商店包含一些用户,我将通过一个方法再添加一个用户。这不会导致useContext()再次运行,从而触发“导入”上下文的所有位置吗?为什么我的上下文通常不应该更新?我认为通过采取行动来改变国家是很常见的?请ClearIfIyes调用操作时,上下文的值不会更改,但传递的ProviderValue中的值会更改(例如,在您的示例中,在new Timer()对象中),对吗?是的,您更改了存储的可观察值,而不是存储本身。上下文仅用于将存储向下传递到树中,之后所有的工作仅由MobX执行(这就是为什么您可以使用单例)啊,好的,那么我只是将存储引用向下传递?谢谢,请在您的问题中添加这一点,我接受您的回答:)我的答案中已经有了“useContext()仅用于获取您的存储值(参考)”。不过我会更新一下我的答案
// Initialize timer somewhere
export const myTimer = new Timer()

// You can use directly in the same file or import somewhere else
import { myTimer } from './file-with-your-timer'

// No props, `myTimer` is directly consumed from the closure or from another file
const TimerView = observer(() => <span>Seconds passed: {myTimer.secondsPassed}</span>)

ReactDOM.render(<TimerView />, document.body)