react 使用hooks
λ yarn add react@16.7.0-alpha.2
λ yarn add react-dom@16.7.0-alpha.2
设置 state
import React, { useState } from "react";
const l = console.log;
function Test() {
const [n, setN] = useState(0);
const [info, setInfo] = useState({
name: "ajanuw",
});
function handleAddN() {
setN(n + 1);
}
function handleInputChange(e) {
setInfo({
...info,
name: e.target.value,
});
}
return (
<div>
<p>test</p>
<p>{n}</p>
<button onClick={handleAddN}>click me</button>
<hr />
<input type="text" value={info.name} onChange={handleInputChange} />
</div>
);
}
useEffect 钩子
它像是 componentDidMount, componentDidUpdate, and componentWillUnmount 这3个钩子
他将在第一次渲染运行,状态改变时运行,返回一个函数来做到 componentWillUnmount 里面做的一些事情
可以执行多个
第2个参数可以监听指定的数据更新才执行
import React, { useState, useEffect } from "react";
const l = console.log;
function Test() {
const [age, setAge] = useState(0);
const [info, setInfo] = useState({
name: "ajanuw",
});
useEffect(
() => {
document.title = `hello ${info.name}`;
let timer = setTimeout(() => {
document.title = `react app`;
}, 2000);
return () => {
l("卸载");
clearTimeout(timer);
};
},
[info],
);
useEffect(
() => {
l("只有age状态更新,才能执行");
},
[age],
);
function handleInputChange(e) {
setInfo({
...info,
name: e.target.value,
});
}
return (
<div>
<input type="text" value={info.name} onChange={handleInputChange} />
</div>
);
}
编写自己的 hooks
就类似编写 高阶组件和渲染组件差不多
function Test() {
const [age, setAge] = useState(0);
const ajanuw = useInput("ajanuw");
const suou = useInput("suou");
useEffect(
() => {
l("只有age状态更新,才能执行");
},
[age],
);
return (
<div>
<input type="text" {...ajanuw} />
<br />
<input type="text" {...suou} />
</div>
);
}
function useInput(iv) {
const [info, setInfo] = useState({
name: iv,
});
useEffect(
() => {
document.title = `hello ${info.name}`;
let timer = setTimeout(() => {
document.title = `react app`;
}, 2000);
return () => {
clearTimeout(timer);
};
},
[info],
);
function handleInputChange(e) {
setInfo({
...info,
name: e.target.value,
});
}
return {
value: info.name,
onChange: handleInputChange,
};
}
useContext
获取 Context 上下文
rx
const l = console.log;
function Test(props) {
const btnRef = useRef();
useEffect(() => {
const click$ = fromEvent(btnRef.current, "click");
click$
.pipe(
map(v => v.type),
throttleTime(2000),
)
.subscribe(l);
return () => {
click$.unsubscribe();
};
});
return (
<>
<button ref={btnRef}>click me</button>
</>
);
}
加载异步数据 更具体的文章
useEffect 传入空数组可以避免在组件更新时激活它,但仅用于组件的安装
import React, { useState, useEffect } from "react";
import axios from "axios";
import Mock from "mockjs";
Mock.mock("/mock/a", "post", opt => {
const body = JSON.parse(opt.body);
return Mock.mock({
code: body.p >= 3 ? 1 : 0,
"data|2": [
{
"id|+1": 1,
label: "@word",
},
],
// data: [],
});
}).setup({
timeout: 1200,
});
const l = console.log;
function Test(props) {
const { status, list, getMore, loading, error } = useDataApi(
0,
[],
"/mock/a",
);
return (
<>
{loading && <div>加载中</div>}
{!!list.length && (
<ul>
<li>
<button onClick={getMore}>加载更多</button>
</li>
{list.map((el, i) => (
<li key={i}>{el.label}</li>
))}
</ul>
)}
{error && <div>暂无数据</div>}
</>
);
}
function useDataApi(initStatus, initData, url) {
const [status, setStatus] = useState(initStatus); // 0 ok, 1 notData, 2 loading
const [p, setP] = useState(1);
const [list, setList] = useState(initData);
useEffect(
() => {
getList();
},
[p],
);
async function getList() {
setStatus(2);
let { code, data } = await axios.post(url, { p });
if (code === 1) {
setStatus(1);
} else {
setList(pdata => [...pdata, ...data]);
setStatus(0);
}
}
function getMore() {
setP(pp => pp + 1);
}
return { status, list, getMore, loading: status === 2, error: status === 1 };
}
export default Test;
react 使用hooks的更多相关文章
- 使用 react 的 hooks 进行全局的状态管理
使用 react 的 hooks 进行全局的状态管理 React 最新正式版已经支持了 Hooks API,先快速过一下新的 API 和大概的用法. // useState,简单粗暴,setState ...
- how to create react custom hooks with arguments
how to create react custom hooks with arguments React Hooks & Custom Hooks // reusable custom ho ...
- React Hooks & react forwardRef hooks & useReducer
React Hooks & react forwardref hooks & useReducer react how to call child component method i ...
- React 与 Hooks 如何使用 TypeScript 书写类型?
React 与 Hooks 如何使用 TypeScript 书写类型? 本文写于 2020 年 9 月 20 日 函数组件与 TS 对于 Hooks 来说是不支持使用 class 组件的. 如何在函数 ...
- react 16 Hooks渲染流程
useState react对useState进行了封装,调用了mountState. function useState<S>( initialState: (() => S) | ...
- 【react】---Hooks的基本使用---【巷子】
一.react-hooks概念 React中一切皆为组件,React中组件分为类组件和函数组件,在React中如果需要记录一个组件的状态的时候,那么这个组件必须是类组件.那么能否让函数组件拥有类组件的 ...
- 【授课录屏】JavaScript高级(IIFE、js中的作用域、闭包、回调函数和递归等)、MySQL入门(单表查询和多表联查)、React(hooks、json-server等) 【可以收藏】
一.JavaScript授课视频(适合有JS基础的) 1.IIFE 2.js中的作用域 3.闭包 4.表达式形式函数 5.回调函数和递归 资源地址:链接:https://pan.baidu.com/s ...
- React Hooks (React v16.7.0-alpha)
:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdow ...
- 理解 React Hooks 心智模型:必须按顺序、不能在条件语句中调用的规则
前言 自从 React 推出 hooks 的 API 后,相信大家对新 API 都很喜欢,但是它对你如何使用它会有一些奇怪的限制.比如,React 官网介绍了 Hooks 的这样一个限制: 不要在循环 ...
随机推荐
- springboot邮件发送与接收读取
发送邮件 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>sp ...
- APP中的图片如何长按可以下载并保存图片到相册
直接上图 方式一: 实现方式二: 方式三:
- Mac上搭建ELK
转载自我的个人博客:http://blog.ywheel.cn/post/2017/03/04/setup_elk_on_mac/ 最近的项目需要对文本数据各字段进行快速检索.组合查询.模糊查询,在架 ...
- Office365 OneDrive Geo Move
Issue Description: 1. Connect to SPO Service. 2. Validate SPO Service OneDrive Geo move compatibilit ...
- float 浮点数与零值0比较大小 ZZ
float x: 千万不要写x==0; 写出float x 与“零值”比较的if语句——一道面试题分析 写出float x 与“零值”比较的if语句 请写出 float x 与“零值”比较的 if ...
- emacs 集成astyle
https://stackoverflow.com/questions/8115460/emacs-save-excursion-not-restoring-point https://github. ...
- hive SQL 行转列 和 列转行
一.行转列的使用 1.问题 hive如何将 a b 1a b 2a b 3c d 4c d ...
- Eclipse安装Git插件及简单操作
0. 前言 说一件事,说起来也是好笑,工作三年半了,还没接触到团队开发,都是一个人小打小闹.因此连Git都没有使用过.感觉好Low的,这一篇,简单讲一下,Eclipse配置Git插件,并提交代码到Gi ...
- 【iCore4 双核心板_uC/OS-II】例程一:认识 uC/OS-II
一.实验说明: 本例程移值入uC/OS-II,建立三个任务,红色和绿色LED分别以固定频率闪烁,并且打开串口工具, 输出浮点数据. 二.源代码下载链接: 链接:https://pan.baidu.co ...
- Deepin 系统下安装VMware并激活
1.打开深度商店:搜索VMware,并下载安装. 2.打开启动器:点击VMware-install. 3.填写管理员密码. 4.下一步,完成安装. 5.打开VMware Workstation,输入密 ...