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();
//开始验证表单,如果原因 通过执行回调发送ajax
this.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!' }],
})(
<Input
prefix={<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!' }],
})(
<Input
prefix={<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;

10分钟学会React Context API的更多相关文章

  1. 10分钟学会VS NuGet包私有化部署

    前言 我们之前实现了打包发布NuGet,但是发布后的引用是公有的,谁都可以访问,显然这种方式是不可取的. 命令版本:10分钟学会Visual Studio将自己创建的类库打包到NuGet进行引用(ne ...

  2. 10分钟学会Linux

    10分钟学会Linux有点夸张,可是能够让一个新手初步熟悉Linux中最重要最主要的知识,本文翻译的英文网页在众多Linux入门学习的资料中还是很不错的. 英文地址:http://freeengine ...

  3. 10分钟学会搭建Android开发环境 Eclipse: The import android.support cannot be resolved

    10分钟学会搭建Android开发环境_隋雨辰 http://v.youku.com/v_show/id_XNTE2OTI5Njg0.html?from=s1.8-1-1.2 The import a ...

  4. 【译】10分钟学会Pandas

    十分钟学会Pandas 这是关于Pandas的简短介绍主要面向新用户.你可以参考Cookbook了解更复杂的使用方法 习惯上,我们这样导入: In [1]: import pandas as pd I ...

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

    写程序必然需要版本控制,哪怕是个人项目也是必须的.我们在开发UWP APP的时候,VS2015默认提供了对微软TFS和Git的支持.考虑到现在Git很火,作为微软系的程序员也不得不学一点防身,以免被开 ...

  6. [译]迁移到新的 React Context Api

    随着 React 16.3.0 的发布,context api 也有了很大的更新.我已经从旧版的 api 更新到了新版.这里就分享一下我(作者)的心得体会. 回顾 下面是一个展示如何使用旧版 api ...

  7. 10分钟了解 react 引入的 Hooks

    "大家好,我是谷阿莫,今天要将的是一个...",哈哈哈,看到这个题我就想到这个开头.最近react 官方在 2018 ReactConf 大会上宣布 React v16.7.0-a ...

  8. [React] Use the new React Context API

    The React documentation has been warning us for a long time now that context shouldn't be used and t ...

  9. React Context API

    使用React 开发程序的时候,组件中的数据共享是通过数据提升,变成父组件中的属性,然后再把属性向下传递给子组件来实现的.但当程序越来越复杂,需要共享的数据也越来越多,最后可能就把共享数据直接提升到最 ...

随机推荐

  1. [转帖]探秘华为(二):华为和H3C(华三)的分道扬镳

    探秘华为(二):华为和H3C(华三)的分道扬镳 https://baijiahao.baidu.com/s?id=1620781715767053734&wfr=spider&for= ...

  2. 【监控实践】【4.2】perfmon监控性能计数器(基于typeperf命令)

    关键词:typeperf typeperf 命令 使用示例: 案例1:#使用typeperf收集windows cpu.内存.硬盘性能 #使用typeperf收集windows cpu.内存.硬盘性能 ...

  3. 【7.10校内test】T1高级打字机

    [题目链接luogu] 这是T1,但是是神仙T1: 对于前100%的数据很好写,直接数组模拟就可以了: (当然也有栈模拟的,据说有模拟炸了的) //50pts#include<bits/stdc ...

  4. BeautifulSoup库的基本元素

    BeautifulSoup库 <html> <body> <p class='title'></p> </body> </html&g ...

  5. [多校联考2019(Round 4 T2)][51nod 1288]汽油补给(ST表+单调栈)

    [51nod 1288]汽油补给(ST表+单调栈) 题面 有(N+1)个城市,0是起点N是终点,开车从0 -> 1 - > 2...... -> N,车每走1个单位距离消耗1个单位的 ...

  6. MY SQL数据库密码最简单的一个方法()

    https://zhidao.baidu.com/question/564368111.html 非常简单的一个修改方法!!!!!!!!!!!!!!!!!!!!! 最简单的方法就是借助第三方工具Nav ...

  7. CSUST 8.3 早训

    A - Settlers' Training CodeForces - 63B 题意 给你一串数字,相同的数字为一组,每次可以给一组中的一个数字加一,问这一串数字全变成K需要多少步? 题解 模拟 C+ ...

  8. 同步锁 synchronized

    package ba; public class Tongbu implements Runnable{ int i=100; public void run(){ while(true){ sell ...

  9. Restful,SAOP,SOA,RPC的基础理解

    什么是Restful restful是一种架构设计风格,提供了设计原则和约束条件,而不是架构.而满足这些约束条件和原则的应用程序或设计就是 RESTful架构或服务. 主要的设计原则: 资源与URI ...

  10. 如何让css隐藏滚动条 兼容谷歌、火狐、IE等各个浏览器

    项目中,页面效果需要展示一个页面的移动端效果,使用的是一个苹果手机样式背景图,咋也没用过苹果,咋也不敢形容. 如下图所示: 在谷歌浏览器如图一滚动条顺利隐藏,但是火狐就如图二了,有了滚动条丑的一批. ...