We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
该方案主要分为三步:1. 基于 hooks 构建 Store 2. 将 Store 基于 context 传递给子组件 3. 子组件更新 Store,并触发渲染,该方案不适用于复杂应用
userStore.tsx
import { useState } from 'react' export default function useUserStore () { const [user, setUser] = useState<IUser>({ }) return { setUser, user, } }
loginStore.tsx
import { useState } from 'react' export default function useLoginStore () { const [login, setLogin] = useState(false) return { login, setLogin, } }
context.tsx
import useUserStore from "./userStore"; import useLoginStore from "./loginStore"; import { createContext } from "react"; export const context = createContext(null); export default function Context({ children }) { const userStore = useUserStore(); const loginStore = useLoginStore(); console.log("userStore", userStore); const contextValue = { userStore, loginStore }; return <context.Provider value={contextValue}>{children}</context.Provider>; }
app.tsx
import Context from "./context"; import Child from "./child"; export default function Index() { return ( <Context> <Child /> </Context> ); }
child.tsx
import { useContext, useEffect } from "react"; import { context } from "./context"; export default function Child() { const store = useContext(context); console.log(store); const { user, setUser } = store?.userStore || {}; const { login, setLogin } = store?.loginStore || {}; useEffect(() => { setTimeout(() => { setUser({ name: "AwesomeDevin" }); setLogin(true); }, 2000); }, [setUser, setLogin]); return ( <div> <p>{user?.name || "未命名"}</p> <p>{login ? "已登陆" : "未登录"}</p> </div> ); }
在线DEMO https://codesandbox.io/s/react-context-ease-store-lv1ibp?file=/src/App.js
The text was updated successfully, but these errors were encountered:
No branches or pull requests
该方案主要分为三步:1. 基于 hooks 构建 Store 2. 将 Store 基于 context 传递给子组件 3. 子组件更新 Store,并触发渲染,该方案不适用于复杂应用
1.构建Store
userStore.tsx
loginStore.tsx
2.将 Store 基于 context 传递给子组件
context.tsx
app.tsx
3.子组件更新 Store,并触发渲染,该方案不适用于复杂应用
child.tsx
在线DEMO https://codesandbox.io/s/react-context-ease-store-lv1ibp?file=/src/App.js
The text was updated successfully, but these errors were encountered: