ReactJS 使用上下文挂钩
Context 提供了一种通过组件树传递数据或状态的方法,而无需通过每个嵌套组件手动向下传递 props。它旨在共享可被视为 React 组件树的全局数据的数据,例如当前经过身份验证的用户或主题(例如颜色、填充、边距、字体大小)。
上下文 API 使用上下文。提供者和上下文。消费者组件传递数据,但编写长功能代码以使用此上下文 API 非常麻烦。所以 useContext 钩子有助于使代码更具可读性,更少冗长,并消除了引入消费者组件的需要。 useContext 钩子是 React 16.8 中的新增功能。
句法:
const authContext = useContext(initialValue);
useContext 接受 React.createContext 提供的值,然后在其值更改时重新渲染组件,但您仍然可以通过使用记忆来优化其性能。
示例:演示useContext Hook使用的程序。在这个例子中,我们有一个按钮,每当我们点击按钮时,onClick 处理程序就会被触发,它会在 useContext 钩子的帮助下更改身份验证状态(默认值为 Nopes)。让我们看看上面代码的输出:
auth-context.js
Javascript
import React from 'react'; // Creating the context object and passing the default values. const authContext = React.createContext({status:null,login:()=>{}}); export default authContext;
Javascript
import React, { useState } from "react"; import Auth from "./Auth"; import AuthContext from "./auth-context"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return (
Javascript
import React, { useContext } from "react"; import AuthContext from "./auth-context"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return (
Are you authenticated?
{auth.status ?Yes you are
:Nopes
}应用程序.js
Javascript
import React, { useState } from "react"; import Auth from "./Auth"; import AuthContext from "./auth-context"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return (
Auth.js
Javascript
import React, { useContext } from "react"; import AuthContext from "./auth-context"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return (
Are you authenticated?
{auth.status ?Yes you are
:Nopes
}
输出: