Create-react-app来学习这个功能: 注意下面代码红色的即可,非常简单.

在小项目里Context API完全可以替换掉react-redux.

修改app.js

import React, { lazy, useState } from "react";
import { Button } from 'antd';
import { HashRouter as Router, Route, Link } from 'react-router-dom';import GlobalContext from './globalContext' // 导入全局context
import './App.css';
//import Hehe from './hehe'  //直接导入会让包变大,使用lazy会让包变小
const Hehe = lazy(() => import("./hehe"));
const T2 = lazy(() => import("./T2"));
const Reg = lazy(() => import(/* webpackChunkName: "reg" */'./reg'));//普通的组件
const PageHeaderWrapper = (prop) => {console.log("子组件刷新...");return (<><div>PageHeaderWrapper Memo:{prop.loading} {new Date().getTime()}</div><div>{prop.content}</div></>
  )
}// React.memo对PageHeaderWrapper组件进行包装,让这个PageHeaderWrapper组件进行包装组件变成可控组件
// React.memo()可接受2个参数,第一个参数为纯函数的组件,第二个参数用于对比props控制是否刷新,true不更新,与shouldComponentUpdate()功能类似。
const Memo = React.memo(PageHeaderWrapper, (prevProps, nextProps) => {console.log(prevProps, nextProps);//return true;return prevProps.loading === nextProps.loading
});//定义一个方法用来测试接受 Provider
const ChangeName = (props) => {return (<GlobalContext.Consumer>{context =><div>{props.title}: {context.name}</div>
      }</GlobalContext.Consumer>
  )
}
//产生一个随机内容的obj 只是为了示例使用
const rand = () => {const a = parseInt(Math.random() * 4, 10);return { name: "aaa" + a }
}//入口文件
const App = () => {const [value, setValue] = useState({ name: "aaa" });return (<GlobalContext.Provider value={value}><div className="App"><header className="App-header"><Memo loading={value.name} content='Memo content' /><Button type="primary" onClick={() => setValue(rand)}>Hehe</Button><p>Provider: {value.name}</p><ChangeName title="changeName"></ChangeName><React.Suspense fallback="T2 loading..."><Hehe /></React.Suspense><Router><Link to="/reg"><div>会员注册</div></Link><Link to="/t2"><div>跳转到异步组件t2</div></Link><Route exact path='/' component={() => <React.Suspense fallback="T2 loading..."> <T2 /> </React.Suspense>} /><Route path='/t2' component={() => <React.Suspense fallback="T2 loading..."> <T2 /> </React.Suspense>} /><Route path='/reg' component={() => <React.Suspense fallback="Reg loading..."> <Reg /> </React.Suspense>} />{/* <Route path='/regsync' component={Reg1} /> 使用同步组件会让包变大 */}</Router></header></div> </GlobalContext.Provider>
  )
}export default App;

reg.js

import React from "react";
import axios from "axios";
import { Form, Icon, Input, Button, Checkbox, Table } from 'antd';const columns = [{title: '姓名',dataIndex: 'name',key: 'name',},{title: 'Email',dataIndex: 'email',key: 'email',},{title: 'Ip',dataIndex: 'ip',key: 'ip',},];//不要在使用class组件,使用函数式组件来,具体看T2.js

class NormalLoginForm extends React.Component {constructor(props){super(props)this.state = {dataSource:[]}}handleSubmit = e => {e.preventDefault();//开始验证表单,如果原因 通过执行回调发送ajaxthis.props.form.validateFields((err, values) => {if (!err) {console.log('表单里的值: ', values);let request=values;request.test="test";//向后台发送axios.get("https://www.easy-mock.com/mock/5a3a2fc5ccd95b5cf43c5740/table_list",{params: request}).then(response=>{//后台返回的值:
            console.log(response.data);this.setState({dataSource:response.data.data})}).catch(e=>{//请求网络原因等失败了处理
          });}});};render() {const { getFieldDecorator } = this.props.form;return (<div  id="components-form-demo-normal-login"><Form onSubmit={this.handleSubmit} className="login-form"><Form.Item>{getFieldDecorator('username', {rules: [{ required: true, message: 'Please input your username!' }],})(<Inputprefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}placeholder="Username"/>,
            )}</Form.Item><Form.Item>{getFieldDecorator('password', {rules: [{ required: true, message: 'Please input your Password!' }],})(<Inputprefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}type="password"placeholder="Password"/>,
            )}</Form.Item><Form.Item>{getFieldDecorator('remember', {valuePropName: 'checked',initialValue: true,})(<Checkbox>Remember me</Checkbox>)}<Button type="primary" htmlType="submit" className="login-form-button">Log in</Button></Form.Item></Form><Table dataSource={this.state.dataSource} columns={columns} style={{background:'#fff'}} /></div>
      );}}const Reg = Form.create({ name: 'normal_login' })(NormalLoginForm);export default Reg;

T2.js

import React, {useState, useEffect} from "react";
import axios from "axios";//组件 里可以使用state,这样就可以不在使用class
const T2=(prop)=>{const [message, setMessage]=useState(()=>{return 'start...';});function temp(){axios.get('http://route.showapi.com/1764-1').then(response=> {console.log(response.data.showapi_res_error);setMessage(response.data.showapi_res_error);})}   useEffect( () => {temp()}, [message]);  // 给useEffect传第二个参数。用第二个参数来告诉react只有当这个参数的值发生改变时,才执行我们传的副作用函数(第一个参数)。return (<><div>T2. message: {message}</div>   </>
    )
}export default T2;

GlobalContext.js
import React from 'react'
const GlobalContext = React.createContext();
export default GlobalContext;

转载于:https://www.cnblogs.com/yuri2016/p/11250592.html

10分钟学会React Context API相关推荐

  1. 10分钟学会Google Map API

    http://space.itpub.net/14734354/viewspace-374828 前几天玩了玩Google的Map API,感觉还不错,很简单.但凡有过任何编程经验的同学,看完以下的教 ...

  2. gatsby_与Gatsby一起使用React Context API

    gatsby I'm a bit late to the party using the new React Context API, I did get to use it the other da ...

  3. pulsar 容量_[Pulsar系列] 10分钟学会Pulsar消息系统概念

    Apache Pulsar Pulsar是一个支持多租户的.高性能的服务与服务之间消息通讯的解决方案,最初由雅虎开发,现在由Apache软件基金会管理. Pulsar在Yahoo的生产环境运行了三年多 ...

  4. UWP开发入门(十九)——10分钟学会在VS2015中使用Git

    原文:UWP开发入门(十九)--10分钟学会在VS2015中使用Git 写程序必然需要版本控制,哪怕是个人项目也是必须的.我们在开发UWP APP的时候,VS2015默认提供了对微软TFS和Git的支 ...

  5. python写好的代码怎么给别人使用-10分钟学会用python写游戏!Python其实很简单!...

    原标题:10分钟学会用python写游戏!Python其实很简单! Python现在非常火,语法简单而且功能强大,很多同学都想学Python!所以在这里给各位看官们准备了高价值Python学习视频教程 ...

  6. 百度贴吧自动发帖_引流网赚之百度贴吧引流窍门:实操引流教程百度贴吧零成本自动顶帖+10分钟学会豆瓣顶帖引流...

    引流网赚之百度贴吧窍门:实操引流教程<百度贴吧零成本自动顶帖>+<10分钟学会豆瓣顶帖引流> 关于百度贴吧的引流方式有很多,像常见的关键词排名引流,比如,百度贴吧引流效果好不好 ...

  7. NiosII软处理器快速入门- 10分钟学会NiosII(1)

    http://hi.baidu.com/hieda/blog/item/7f69080e9efb80ce7bcbe13d.html Nios简单介绍: Nios II是一个用户可配置的通用RISC嵌入 ...

  8. 手机版python3h如何自制游戏_Python 飞机大战|10 分钟学会用 python 写游戏

    Python 飞机大战|10 分钟学会用 python 写游戏 2018 年 python 语言大火, 这把火看趋势已然延续到了 2019 年! 除了在科学计算领域 python 有用武之地之外, 在 ...

  9. #今日论文推荐#1小时学会走路,10分钟学会翻身,世界模型让新生机器狗掌握多项技能

    #今日论文推荐#1小时学会走路,10分钟学会翻身,世界模型让新生机器狗掌握多项技能 人类宝宝在出生后的第1年里,就会逐渐掌握协调能力,学习坐.立.翻滚和爬行. 那么机器人呢? 机器人能完成多复杂的任务 ...

最新文章

  1. 百度商品识别心得笔记
  2. sharepoint权限操作(记录以备忘)
  3. myeclipse中,项目上有个叉报错,文件没有错误
  4. Qt学习笔记之文件处理
  5. zw版【转发·台湾nvp系列Delphi例程】HALCON DispCross
  6. 设置Apache Hadoop多节点集群
  7. 计算机网络是将地理知识,计算机网络的基础知识精选.ppt
  8. linux mmap 内存映射 mmap() vs read()/write()/lseek()
  9. phpstudy编写html,phpStudy简介
  10. springmvc知识点
  11. PreScan笔记(1)——入坑之简单介绍和Demo
  12. Apache CXF 框架结构和基本原理
  13. STM32F107 资料
  14. r语言 面板数据回归_在R语言中进行面板数据分析
  15. ios 监测网页按钮_关于iOS加载WebView监控网页上的点击事件
  16. [阿里天池]Baby Goods Info Data
  17. 数据血缘图谱升级方案设计与实现
  18. 模型的评估指标(一)
  19. douyin_xl,xa,xg,xk
  20. Unity间接光 ibl(基于图像的渲染)和SH(球谐光照)

热门文章

  1. asp.net 验证码
  2. silverlight1.0绝对是垃圾,中文乱码,没治!
  3. linux基础试卷笔试,顽石系列:Linux基础笔试
  4. 2019ug最新版本是多少_NX1847:2019年最新版本,从某种意义上来说,也将是终极版本...
  5. python 写入excel_实用小工具python数组快速写入excel表格
  6. 062_JavaScript异常
  7. 025_html表格
  8. 013_html水平线
  9. 注册界面php mysql_php:用户登录注册并存入数据库的简单网页示例
  10. ue4 无限地图_RPG游戏开发日志13:无限地图的实现