跳至主要內容

提供者

概觀

<Provider> 元件讓 Redux store 可提供給任何需要存取 Redux 儲存的巢狀元件。

由於 React Redux 應用程式中的任何 React 元件都能連接到儲存,因此大多數應用程式會在最上層呈現 <Provider>,並讓整個應用程式的元件樹包含在其中。

掛勾connect API 接著可透過 React 的 Context 機制存取已提供的儲存執行個體。

道具

interface ProviderProps<A extends Action = AnyAction, S = any> {
/**
* The single Redux store in your application.
*/
store: Store<S, A>

/**
* An optional server state snapshot. Will be used during initial hydration render
* if available, to ensure that the UI output is consistent with the HTML generated on the server.
* New in 8.0
*/
serverState?: S

/**
* Optional context to be used internally in react-redux. Use React.createContext()
* to create a context to be used.
* If this is used, you'll need to customize `connect` by supplying the same
* context provided to the Provider.
* Set the initial value to null, and the hooks will error
* if this is not overwritten by Provider.
*/
context?: Context<ReactReduxContextValue<S, A> | null>

/** Global configuration for the `useSelector` stability check */
stabilityCheck?: StabilityCheck

/** The top-level React elements in your component tree, such as `<App />` **/
children: ReactNode
}

一般來說,您只需要傳遞 <Provider store={store}>

您可以提供一個情境執行個體。如果您這樣做,也需要將相同的情境執行個體提供給所有連接元件。未提供正確的情境會造成這個執行時期錯誤

不變式違規

在 Connect(MyComponent) 的「store」情境中找不到。請將根元件包裝在 <Provider> 中,或將自訂 React 情境提供者提供給 <Provider>,以及將對應的 React 情境使用者提供給連線選項中的 Connect(Todo)。

React 18 SSR 使用

自 React-Redux v8 起,<Provider> 現已接受 serverState prop,供 SSR 保持濕潤場景使用。如果你呼叫 hydrateRoot 以避免保濕不一致,這是必要的。

你應該傳遞伺服器中序列化狀態的總量作為 serverState prop,React 將使用此狀態進行初始保濕渲染。然後,它將套用設定處理過程中在用戶端發生的變更的所有更新。

範例

基本用法

在以下範例中,<App /> 組件是我們的根層組件。這表示它是在我們組件階層的最頂層。

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import { App } from './App'
import createStore from './createReduxStore'

const store = createStore()

// As of React 18
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Provider store={store}>
<App />
</Provider>,
)

React 18 SSR 保濕

在這個範例中,用戶端收到了由伺服器渲染的 HTML,以及附加至 window 的 Redux 序列化狀態。序列化狀態用於預先填入儲存的內容和傳遞作為 serverState prop 至 <Provider>

src/index.ts
import { hydrateRoot } from 'react-dom/client'
import { configureStore } from '@reduxjs/toolkit'
import { Provider } from 'react-redux'

const preloadedState = window.__PRELOADED_STATE__

const clientStore = configureStore({
reducer: rootReducer,
preloadedState,
})

hydrateRoot(
document.getElementById('root'),
<Provider store={clientStore} serverState={preloadedState}>
<App />
</Provider>,
)