- 首先我們需要創建一個context來掛載我們useReducer創建的redux
//context.js 創建context import { createContext } from 'react'; export default createContext(null);
- 在context上掛載我們useReducer創建出的redux,通過context提供的Provider組件
//APP父組件 掛載redux import reducer from './store/reducer'; import PersonalContext from '../../context'; const [personalState, personalDispatch] = useReducer(reducer, { name: '123' }); <PersonalContext.Provider value={{ personal: { personalState, personalDispatch } }}> <Home /> </PersonalContext.Provider>
- 接下來我們就可以通過這個context來獲取到掛載在上面的redux,使用方法有兩種:useContext方法和context提供的Consumer組件
//Home子組件 使用redux import React, { useContext } from 'react'; import Personale from '../../context'; const Home= () => { const personal = useContext(Personale); console.log(personal); return ( <Personale.Consumer> {value=>{console.log(value)}} </Personale.Consumer> ); }; export default Home;
兩種使用方法打印出來的結果相同:
----------------------------下面是我在一個具體場景中的運用---------------------------
場景:在一個動態生成的多個組件里面,可能一個組件依賴於另一個組件的值而變化
我們首先想到的是redux,這一個可以保存供多個組件使用的解決方案
方法:創建我們自己的reducer,使用useContext提供使用
const { PageData, activeComponent } = useContext(PageContext);
在具體的場景里面,我的PageData存儲的頁面信息,activeComponent當前選中的頁面組件的索引
不出所料,我們果然可以正確使用,
bug:但是,在拉入下一個組件的時候,報錯如下
Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement in React Hooks
百度之后https://stackoverflow.com/questions/53472795/uncaught-error-rendered-fewer-hooks-than-expected-this-may-be-caused-by-an-acc發現元問題出現的原因:
我們的組件動態生成是存在判斷條件的,也就是通過判斷組件的type屬性選擇對應的組件
switch (type) { case 'Array': EditorComp = () => { return <React.Fragment>{UseArrInput(props, value, handleChange)}</React.Fragment>; }; break; case 'Object': EditorComp = () => { return <React.Fragment>{UseObjectInput(props, value, handleChange)}</React.Fragment>; }; break; default: EditorComp = () => { return <React.Fragment>{Editor(props, value, handleChange)}</React.Fragment>; }; break; }
而react的鈎子官方要求如下
不要在循環,條件或嵌套函數中調用Hook。相反,始終在React函數的頂層使用Hooks。通過遵循此規則,您可以確保每次組件呈現時都以相同的順序調用Hook。這就是允許React在多個useState
和useEffect
調用之間正確保留Hook狀態的原因。
最終解決方案:選擇在沒有判斷條件的頂層使用useContext,將獲取的值,作為參數傳給組件使用!