[英]Using React Hooks for Data Provider and Data Context
我目前正在修改我的DataProvider
,使用 React Hooks 將它從一個類組件更新為一個功能組件。
我相信我的問題在於我設置上下文使用者的方式,但我還沒有找到測試這個的好方法。
數據提供者.js
import React, { createContext } from "react";
const DataContext = createContext();
export const DataProvider = (props) => {
const [test, setTest] = React.useState("Hello");
return (
<DataContext.Provider value={test}>{props.children}</DataContext.Provider>
);
};
export const withContext = (Component) => {
return function DataContextComponent(props) {
return (
<DataContext.Consumer>
{(globalState) => <Component {...globalState} {...props} />}
</DataContext.Consumer>
);
};
};
所以我的withContext
函數應該接收一個組件並將上下文提供者的道具傳遞給它。
我嘗試將我的測試狀態拉入組件中。
import React from "react";
import style from "./DesktopAboutUs.module.css";
import { withContext } from "../../DataProvider";
const DesktopAboutUs = ({ test }) => {
return (
<div className={style.app}>
<div>{test}</div>
</div>
);
};
export default withContext(DesktopAboutUs);
沒有數據顯示為test
。 對我來說,這表明我的withContext
函數沒有正確地從Provider
接收道具。
因為您傳遞了value={test}
, globalState
是一個字符串,而不是具有test
屬性的對象。
這些解決方案中的任何一個都會產生您期望的結果:
value
的丙DataContext.Provider
使用value={{ test }}
而不是value={test}
如果打算globalState
包含多個道具。globalState
到test
的支柱Component
使用test={globalState}
代替{...globalState}
如果你不打算globalState
含有多種道具。 const DataContext = React.createContext(); const DataProvider = (props) => { const [test, setTest] = React.useState("Hello"); return ( <DataContext.Provider value={{ test }}> {props.children} </DataContext.Provider> ); }; const withContext = (Component) => (props) => ( <DataContext.Consumer> {(globalState) => <Component {...globalState} {...props} />} </DataContext.Consumer> ); const DesktopAboutUs = ({ test }) => ( <div>{test}</div> ); const DesktopAboutUsWithContext = withContext(DesktopAboutUs); ReactDOM.render( <DataProvider> <DesktopAboutUsWithContext /> </DataProvider>, document.querySelector('main') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script> <main></main>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.