你能解釋一下為什么在使用帶有 React Context 的 mobx 時我需要將我的應用程式包裝在 Store Provider 中。我的意思是:
// Create Counter Store
class CounterStore {
constructor() {
makeAutoObservable(this)
this.num = 0
}
inc() { this.num }
}
// Create React Context with store
const StoreContext = React.createContext(new CounterStore())
// Create hook for usage context
const useStore = () => React.useContext(StoreContext)
// Create component
const Counter = observer(() => {
const counterStore = useStore()
return (
<>
<div>{counterStore.num}</div>
<button onClick={() => counterStore.inc()}>
inc num
</button>
</>
)
})
// Create App component
const App = () => {
return (
<Counter />
)
}
好的,一切正常,我可以訪問我的計數器組件內的商店。
但我仍然沒有將我的應用程式包裝到商店提供程式中,例如:
/// same code as above with little change
// Now create context with no value:
const StoreContext = React.createContext()
// And create Provider with store.
const StoreProvider = ({children}) => {
return <StoreContext.Provider value={new CounterStore()}>
{children}
</StoreContext.Provider>
}
Then wrap App component with provider:
render(
<StoreProvider>
<App />
</StoreProvider>,
document.getElementById("root")
);
這段代碼也有效。但我不明白為什么我需要創建 SroreProvider 并用它包裝我的應用程式,如果沒有它一切正常
uj5u.com熱心網友回復:
簡短回答:Provider如果您的背景關系具有默認存盤值,則不一定需要將所有內容包裝起來。一切都會很好,因為 MobX 為觀察者組件創建了自己的訂閱機制,允許它們重新渲染。(也值得閱讀此檔案以了解為什么如果您不使用 MobX,您可能需要背景關系)
更重要的是,在這種情況下,您甚至可能根本不需要背景關系。您可以只創建存盤的單例實體并直接將其匯入到您需要的地方,而不必理會提供者。
但有時您可能希望與提供者有背景關系。例如用于服務器端渲染,或用于測驗目的。就像想象你的inc方法進行了一些 api 呼叫。但是對于測驗您不想這樣做,并且在測驗時您可以用不同的商店替換您的商店:
const TestStoreProvider = ({children}) => {
// With provider you can different store there
return <StoreContext.Provider value={new CounterStoreForTests()}>
{children}
</StoreContext.Provider>
}
在這種情況下,您可以將其Provider視為組件的依賴注入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322067.html
上一篇:更新地圖回圈中的特定專案
