标签:tar 组件 NPU 更新 mount app hello test 指定
λ yarn add react@16.7.0-alpha.2
λ yarn add react-dom@16.7.0-alpha.2
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>
);
}
它像是 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>
);
}
就类似编写 高阶组件和渲染组件差不多
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,
};
}
标签:tar 组件 NPU 更新 mount app hello test 指定
原文地址:https://www.cnblogs.com/ajanuw/p/10128129.html