解决痛点
当组件树层级很深时,组件之间需要使用同一份数据时,通过组件的提升到父组件中用props传参的方式太过麻烦。
应用需求场景
1.兄弟组件之间共享state(即同一份数据),useContext适合
2.爷孙组件(特别是组件树层级很深时)之间共享state,useContext适合
3.父子组件之间共享state,建议用useState+props实现普通父子组件之间传参即可。
4.项目工程各个组件全局共享state: 建议用UmiJS的插件@umijs/plugin-initial-state和@umijs/plugin-model一起搭配实现。
小结:context的使用场景就是“在组件树中,不同层级需要访问相同的数据源时,可以利用context,进行组件之间的通信或者订阅指定的context对象”。
特性
上下文变量的一种订阅方式 适合跨越组件层级直接传递变量,实现数据共享 createContext 和 useContext 配套结合使用实现state共享 <MyContext.Provider value={{ setStep, setCount, setNumber, fetchData }} /> 里面的方法可能越来越多,变得越来越臃肿,这时候配合useReducer,vaule={{dispatch}更省事。 只有一层的父子组件之间传参,使用普通的useState+props进行父子组件传参更适合。
用法示例
示例1:useContext+useState的定义共享数据
父组件parentComponent.tsx: import React, { useContext } from "react"; import ReactDOM from "react-dom";
const TestContext= React.createContext({}); function App() { return ( <TestContext.Provider value={{ username: '热水', }} > }
子组件1:sub1Component.tsx:
const sub1Component= () => { const { username } = useContext(TestContext)
return (
{username}
return (
1 message for {username}
父组件: import React, { useReducer } from 'react'; import Child from './Child'; import { MyContext } from './context-manager';
const initState = { count: 0, step: 0, number: 0 };
const reducer = (state, action) => { switch (action.type) { case 'stepInc': return Object.assign({}, state, { step: state.step + 1 }); case 'numberInc': return Object.assign({}, state, { number: state.number + 1 }); case 'count': return Object.assign({}, state, { count: state.step + state.number }); default: return state; } }
export default (props = {}) => { const [state, dispatch] = useReducer(reducer, initState); const { step, number, count } = state;
return (
<MyContext.Provider value={{ dispatch }}>
<Child step={step} number={number} count={count} />
</MyContext.Provider>
);
} 子组件: import React, { useContext, memo } from 'react';
import { MyContext } from './context-manager';
export default memo((props = {}) => { const { dispatch } = useContext(MyContext);
return (
<div>
<p>step is : {props.step}</p>
<p>number is : {props.number}</p>
<p>count is : {props.count}</p>
<hr />
<div>
<button onClick={() => { dispatch({ type: 'stepInc' }) }}>step ++</button>
<button onClick={() => { dispatch({ type: 'numberInc' }) }}>number ++</button>
<button onClick={() => { dispatch({ type: 'count' }) }}>number + step</button>
</div>
</div>
);
}); 示例3:不用useContext,用普通的props完成父子函数组件传参:
父组件(函数组件): import Child from 'Child';//引入子组件
const Father =() => {
//父组件要传递给子组件的函数
const func = () => {
console.log("父组件")
}
return <Child func=func>
}
子组件(函数组件): const Child = (props)=> {
const handleClick = () => {
const {func}=props;
func();
}
return <button onclick={this.handleClick}>子组件</button>
}