1 useState
2 useEffect
3 useContext
4 useReducer
Article directory
3 useContext() shared state hook
useContext
The role of is to achieve data sharing, solve the problem of passing values between components, and directly pass variables across component levels. That is, a technology that provides global shared data for the component tree it contains.
3.1 Create Context
The root component introduces createContext
the method and creates a Context
import React, {
createContext } from 'react';
const ContextName = createContext();
3.2 Passing values to descendant components
Use ContextName.Provider
the component the descendant components that need to accept data,
And provide the data to share via value
the attribute .
<ContextName.Provider value={
count}>
<Child />
</ContextName.Provider>
3.3 Descendant components get the value passed in
Use in descendant components to get the value passed in useCountext
by the root component,
useContext
Pass the defined in the root component toContextName
import React, {
useContext } from 'react';
const Child = () => {
const count = useContext(ContextName);
return <p>子组件获得的点击数量:{
count}</p>;
};
3.4 Complete example
import React, {
useState, createContext, useContext } from "react";
const ContextName = createContext();
const Child = () => {
// 后代组件
const count = useContext(ContextName);
return <p>子组件获得的点击数量:{
count}</p>;
};
const Parent = () => {
// 根组件
const [count, setCount] = useState(0);
return (
<div>
<p>父组件点击数量:{
count}</p>
<button onClick={
() => setCount(count + 1)}>{
"点击+1"}</button>
<ContextName.Provider value={
count}>
<Child />
</ContextName.Provider>
</div>
);
};
export default Parent;