Ant Design Pro V5精讲(基础篇五):useContext

本文介绍了在React组件树中如何利用context进行跨层级的状态共享,包括使用useContext和useReducer的场景。示例展示了在父组件中创建context,子组件通过useContext获取数据,以及如何用useReducer替代繁琐的props传递,简化代码。此外,还提到了在简单父子组件间使用useState和props进行传参的情况。
摘要由CSDN通过智能技术生成

解决痛点

  当组件树层级很深时,组件之间需要使用同一份数据时,通过组件的提升到父组件中用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 (
    <div>
      <p>{username}</p>
    </div>
  )
}
子组件2:sub2Compnent.tsx:
const sub2Compnent= () => {
  const { username } = useContext(TestContext)

  return (
    <div>
      <p>1 message for {username}</p>
    </div>
  )
}

示例2:useContext+useReducer

父组件:
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>  
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值