我試圖不使用 Redux。所以我堅持使用 useContext 和 useReducer 進行全域狀態管理。我的問題:我無法使用調度更新子組件的狀態。
讓我更詳細地解釋一下。我的背景關系檔案非常簡單:
import React, { createContext } from "react";
const ActivateContext = createContext();
export default ActivateContext;
我將它匯入 App.js 并將其包裹在導航中的根組件周圍:
import React, { useState, useReducer } from "react";
import Navigation from "./Navigation";
import ActivateContext from "./store/activate-context";
const Reducer = (state, action) => {
if (action.type === "ACTIVATE_IT") return true;
};
export default function App() {
let initialState = false;
const [state, dispatch] = useReducer(Reducer, initialState);
return (
<Provider store={store}>
<ActivateContext.Provider value={{activeStatus: state, activeDispatch: dispatch}}>
<Navigation />
</ActivateContext.Provider>
</Provider>
);
然后我在名為“Child”的子組件中匯入“ActivateContext”。我將所有內容保存在常量“激活”中。然后我在名為“access”的道具中使用“激活”:
import React, {useContext} from "react";
import ActivateContext from "../../../store/activate-context";
function Child (props) {
const activated = useContext(ActivateContext);
<MightComponent title="So Amazing" access={activated} />
我嘗試向組件“Child”添加一個按鈕來更改 App.js 中的狀態,但沒有任何反應:
<TouchableOpacity
onClick={() => ActivateContext.activeDispatch("ACTIVATE_IT")}
>
<Text>Testit</Text>
</TouchableOpacity>
我知道 useContext 有效。如果我在 App.js 中將“initialState”設定為 true 并將其作為值提供給我的提供程式,則子組件中的“訪問”道具會收到“true”,這會使組件更改其樣式:
<ActivateContext.Provider value={initialState}>
<Navigation />
</ActivateContext.Provider>
但是我沒有設法使用 useContext 也將調度函式向下傳遞到組件樹......
任何幫助深表感謝。
謝謝!
uj5u.com熱心網友回復:
我認為您正在嘗試在onClick函式中錯誤地訪問您的背景關系值,這里是:
onClick={() => ActivateContext.activeDispatch("ACTIVATE_IT")}
您正在將具有兩個欄位的物件傳遞給您的value道具:
<ActivateContext.Provider value={{activeStatus: state, activeDispatch: dispatch}}>
<Navigation />
</ActivateContext.Provider>
因此,您應該能夠在您的頁面中訪問這兩個值,執行以下操作:
const {activeStatus, activeDispatch} = useContext(ActivateContext);
而且,由于您的調度需要一個具有型別欄位的物件,因此您的onClick函式將類似于:
onClick={() => activeDispatch({type: "ACTIVATE_IT"})}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/467117.html
