今天教學結合了 useContext ,把props 不用當傳家寶傳下去了,可以透過 useContext 管理 state,這還不夠好用,只需要結合到reducer,可以讀取,還可以操作,才是真的好用。
useReducer 教學 + Demo ( 實際Demo內容此看此文章 ):
- 建立 React.createContext()
//context.js import React from "react"; export const CatStateContext = React.createContext();
2. 利用 context 建立一個Provider 初始化 state,以供下面的子元素可以使用
//provider.js import React from "react"; import Content from "./content"; import { CatStateContext } from "./context"; const initialState = { character: [ { id: "01", name: "湯姆貓", feature: "很蠢" }, { id: "02", name: "傑立鼠", feature: "很賤" }, { id: "03", name: "母湯貓", feature: "哥哥~母湯喔!" } ], startCatchMouse: false }; export const ProviderContext = () => { return ( <CatStateContext.Provider value={initialState}> <Content context={CatStateContext} /> </CatStateContext.Provider> ); };
3. 取得state值
匯入State有兩種方式:
1. import
2. 使用props傳入 ( 不建議 ,因為跟一般傳props方法一樣)
拿到 context 後,使用React.useContext (context) 就可以開始取得值了
//content.js import React, { useContext } from "react"; import { CatStateContext } from "./context"; export default (props) => { const state = useContext(CatStateContext); const state2 = useContext(props.context); const table = state.character.map((value) => { return ( <div key={value.id} style={{ border: "1px solid green" }}> <p>編號 {value.id}</p> <h3>名字 {value.name}!</h3> <h3>特徵 {value.feature}</h3> </div> ); }); return ( <div> {table} <p>{state2.startCatchMouse === false ? "休息" : "開始抓貓"}</p> </div> ); };
主程式:
//index.js import React from "react"; import ReactDOM from "react-dom"; import { ProviderContext } from "./provider"; class App extends React.Component { constructor(props) { super(props); this.state = { name: "湯姆貓表" }; } render() { return ( <div> <h1>{this.state.name}</h1> <ProviderContext /> </div> ); } } ReactDOM.render(<App />, document.getElementById("app"));
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記