ReactJS useContext使用

ReactJS useContext使用

  • 前言
  • 版本要求
  • 步骤
    • 1.创建Context
    • 2.使用MyContext.Provider提供value
    • 3.使用useContext(MyContext)获得数值value
  • 易错点

前言

hook函数是React 16.8后新推出的特性,可以取代class的写法。

版本要求

react > 16.8

步骤

1.创建Context

2.使用MyContext.Provider提供value

3.使用useContext(MyContext)获得数值value

//MainPage.js
import React from 'react'
import ChildPage from './ChildPage'
export const MyContext = React.createContext();
function MainPage(){
	return (
	    
) } export default MainPage;
//ChildPage.js
import React from 'react'
import {MyContext} from './MainPage'
function ChildPage(){
	return (
	    

{useContext(MyContext)}

) } export default ChildPage;

易错点

  1. useContext是新增的Hook函数,目前版本(16.8)里只能在function函数体内使用,不要在class组件内使用,也不要在条件语句内使用
  2. Context需要在多个文件中传递数据,所以要在定义Context的地方加入export,在需要使用数据地方import进来,注意import的时候一定要加上花括号{MyContext}(原因请关注默认export和命名export的区别)
  3. 不要在一个文件中provider提供完数据后,马上useContext消费数据,可能会取不到值。

你可能感兴趣的:(ReactJS useContext使用)