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 的这样一个限制: 不要在循环 ...
随机推荐
- 使用Regsvr32.exe程序注册/注销ActiveX控件
使用ActiveX控件之前需要注册该控件. 使用Regsvr32.exe程序可以注册.注销ActiveX控件. Regsvr32.exe程序位于Windows目录的system子目录下. 可以在cmd ...
- Win 10 System Restore Fail 0x80070091
Question: Below about says it all. I tried SysRes from two points, both with same failure. System R ...
- 使用python实现深度神经网络 2(转)
https://blog.csdn.net/oxuzhenyi/article/details/73026796 导数与梯度.矩阵运算性质.科学计算库numpy 一.实验介绍 1.1 实验内容 虽然在 ...
- BABLE 原理
1.babel转换原理 2.主要过程 (1)babylon进行解析得到AST (2)babel-traverse插件对AST树进行遍历转译得到新的AST树 (3)babel-generator将AST ...
- mybatis检测mysql表是否存在
1.优先使用information_schema来检查,如果没有查询这个的权限则使用show tables来检查. mapper: import java.util.Map; import org.a ...
- mysql字符串用法
replace(str,from_str,to_str) --用字符串to_str替换字符串str中的子串from_str并返回 --mysql> select replace('www.mys ...
- Flutter Android 真机调试指南
操作预览: 准备一条数据线,并连接电脑和手机: 使用 flutter devices 查看设备能否找到: 在 Android studio 中选择你的真机,然后点击 [debug]: 真机自动安装Ap ...
- Python实现下载文件的三种方法
下面来看看三种方法是如何来下载zip文件的:方法一: import urllib print "downloading with urllib" url = 'http://www ...
- Visual Studio编辑器“智能提示(IntelliSense)”异常的解决方案
1.删除工程中的 .suo 文件. 2.重启vs
- Generate google sitemap xml
方式一. XNamespace xNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9"; XNamespace xht ...