react上下文context使用教程
context优缺点:
优点:跨组件访问数据
缺点:react组件树种某个上级组件shouldComponetUpdate 返回false,当context更新时,不会引起下级组件更新
定义全局context对象
globalContext.js
import React from 'react'
const GlobalContext = React.createContext()
export default GlobalContext
根组件引入GlobalContext,并使用GlobalContext.Provider(生产者)
<GlobalContext.Provider
value={{
background: 'green',
color: 'white',
content:this.state.content,
methodA:this.changeStateByChildren,
global: { ...this.state, userInfo: this.props.userinfo },
changeGlobalState: (state) => {
this.setState({ ...state });
}, //通过函数改变值
}}
>
//注意:传入的value为根context对象的值,如果是动态的,使用状态管理
</GlobalContext.Provider>
改变值
改变context的值
import GlobalContext from "globalContext.js";
class Fbf extends Component {
static contextType = GlobalContext;
// 申明静态变量、contextType 将 context 直接赋值于 contextType
//contextType 只能在类组件中使用
//一个组件如果有多个 consumer , contextType 只对其中一个有效,所以说,contextType 只能有一个
componentDidMount() {
const context = this.context;
// 在函数中 可以直接 访问 this.context 获取共享变量、这样就可以不使用 consumer
context.changeGlobalState({
RegionId: selectedOptions[len].key,
RegionName: selectedOptions[len].value,
}); //通过函数改变值
}
componentWillReceiveProps = (nextProps, nextContext) => {
if (
nextContext.global.userRegion &&
this.context.global.userRegion != nextContext.global.userRegion
) {
this.getData(nextContext.global.userRegion);
}
}; //如果值有变化 则更新
}
使用值
需要使用context值的某个组件
import GlobalContext from "globalContext.js";
class Fbf extends Component {
const context = useContext(GlobalContext);
//useContext()钩子函数用来引入Context对象,从中获取context 属性
}
欢迎交流!!!