1、Hook
1.1 为什么会出现hook
1.2 useState
import React, { memo, useState } from "react";
const App = memo(() => {
const [message, setMessage] = useState("Hello World");
const [count, setCount] = useState(100);
const [banners, setBanners] = useState([]);
function changeMessage() {
setMessage("你好啊, 李银河!");
}
return (
<div>
<h2>App: {message}</h2>
<button onClick={changeMessage}>修改文本</button>
</div>
);
});
export default App;
1.3 useEffect
import React, { memo, useEffect } from 'react'
import { useState } from 'react'
const App = memo(() => {
const [count, setCount] = useState(0)
// 负责告知react, 在执行完当前组件渲染之后要执行的副作用代码
useEffect(() => {
// 1.监听事件
// const unubscribe = store.subscribe(() => {
// })
// function foo() {
// }
// eventBus.on("why", foo)
console.log("监听redux中数据变化, 监听eventBus中的why事件")
// 返回值: 回调函数 => 组件被重新渲染或者组件卸载的时候执行
return () => {
console.log("取消监听redux中数据变化, 取消监听eventBus中的why事件")
}
})
return (
<div>
<button onClick={e => setCount(count+1)}>+1({count})</button>
</div>
)
})
export default App
import React, { memo, useEffect } from 'react'
import { useState } from 'react'
const App = memo(() => {
const [count, setCount] = useState(0)
// 负责告知react, 在执行完当前组件渲染之后要执行的副作用代码
useEffect(() => {
// 1.修改document的title(1行)
console.log("修改title")
})
// 一个函数式组件中, 可以存在多个useEffect
useEffect(() => {
// 2.对redux中数据变化监听(10行)
console.log("监听redux中的数据")
return () => {
// 取消redux中数据的监听
}
})
useEffect(() => {
// 3.监听eventBus中的why事件(15行)
console.log("监听eventBus的why事件")
return () => {
// 取消eventBus中的why事件监听
}
})
return (
<div>
<button onClick={e => setCount(count+1)}>+1({count})</button>
</div>
)
})
export default App
import React, { memo, useEffect } from "react";
import { useState } from "react";
const App = memo(() => {
const [count, setCount] = useState(0);
const [message, setMessage] = useState("Hello World");
// 只收到count的影响
useEffect(() => {
console.log("修改title:", count);
}, [count]);
// 不受任何影响 类似生命周期的挂载和卸载
useEffect(() => {
console.log("发送网络请求, 从服务器获取数据");
return () => {
console.log("会在组件被卸载时, 才会执行一次");
};
}, []);
return (
<div>
<button onClick={(e) => setCount(count + 1)}>+1({count})</button>
<button onClick={(e) => setMessage("你好啊")}>
修改message({message})
</button>
</div>
);
});
export default App;
1.4 useContext
import { createContext } from "react";
const UserContext = createContext();
const ThemeContext = createContext();
export { UserContext, ThemeContext };
import React, { memo, useContext } from 'react'
import { UserContext, ThemeContext } from "./context"
const App = memo(() => {
// 使用Context
const user = useContext(UserContext)
const theme = useContext(ThemeContext)
return (
<div>
<h2>User: {user.name}-{user.level}</h2>
<h2 style={{color: theme.color, fontSize: theme.size}}>Theme</h2>
</div>
)
})
export default App
- 依然需要在index.js使用context
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<UserContext.Provider value={{name: "why", level: 99}}>
<TokenContext.Provider value={'coderwhy'}>
<App />
</TokenContext.Provider>
</UserContext.Provider>
);
1.5 useReducer
import React, { memo, useReducer } from 'react'
// import { useState } from 'react'
function reducer(state, action) {
switch(action.type) {
case "increment":
return { ...state, counter: state.counter + 1 }
case "decrement":
return { ...state, counter: state.counter - 1 }
case "add_number":
return { ...state, counter: state.counter + action.num }
case "sub_number":
return { ...state, counter: state.counter - action.num }
default:
return state
}
}
// useReducer+Context => redux
const App = memo(() => {
// const [count, setCount] = useState(0)
const [state, dispatch] = useReducer(reducer, { counter: 0, friends: [], user: {} })
// const [counter, setCounter] = useState()
// const [friends, setFriends] = useState()
// const [user, setUser] = useState()
return (
<div>
{/* <h2>当前计数: {count}</h2>
<button onClick={e => setCount(count+1)}>+1</button>
<button onClick={e => setCount(count-1)}>-1</button>
<button onClick={e => setCount(count+5)}>+5</button>
<button onClick={e => setCount(count-5)}>-5</button>
<button onClick={e => setCount(count+100)}>+100</button> */}
<h2>当前计数: {state.counter}</h2>
<button onClick={e => dispatch({type: "increment"})}>+1</button>
<button onClick={e => dispatch({type: "decrement"})}>-1</button>
<button onClick={e => dispatch({type: "add_number", num: 5})}>+5</button>
<button onClick={e => dispatch({type: "sub_number", num: 5})}>-5</button>
<button onClick={e => dispatch({type: "add_number", num: 100})}>+100</button>
</div>
)
})
export default App
1.6 useCallback
import React, { memo, useState, useCallback, useRef } from "react";
// useCallback性能优化的点:
// 1.当需要将一个函数传递给子组件时, 最好使用useCallback进行优化, 将优化之后的函数, 传递给子组件
// props中的属性发生改变时, 组件本身就会被重新渲染
const HYHome = memo(function (props) {
const { increment } = props;
console.log("HYHome被渲染");
return (
<div>
<button onClick={increment}>increment+1</button>
{/* 100个子组件 */}
</div>
);
});
const App = memo(function () {
const [count, setCount] = useState(0);
const [message, setMessage] = useState("hello");
console.log("App组件被重新渲染");
// 闭包陷阱: useCallback
// 闭包陷阱的结果可以参考如下案例 bar2()始终拿到的是why
// 参数1 函数
// 参数2 依赖值 只有依赖值发生变化 函数才会更新
// const increment = useCallback(
// function foo() {
// console.log("increment");
// setCount(count + 1);
// },
// [count]
// );
// 进一步的优化: 当count发生改变时, 也使用同一个函数(了解)
// 做法一: 将count依赖移除掉, 缺点: 闭包陷阱
// 做法二: useRef, 在组件多次渲染时, 返回的是同一个值
const countRef = useRef();
countRef.current = count;
const increment = useCallback(function foo() {
console.log("increment");
setCount(countRef.current + 1);
}, []);
// 普通的函数
// 如果使用过方法的话 每次传入组件的props的数值都是新的会导致组件被重新渲染
// const increment = () => {
// setCount(count + 1);
// };
return (
<div>
<h2>计数: {count}</h2>
<button onClick={increment}>+1</button>
<HYHome increment={increment} />
<h2>message:{message}</h2>
<button onClick={(e) => setMessage(Math.random())}>修改message</button>
</div>
);
});
// function foo(name) {
// function bar() {
// console.log(name)
// }
// return bar
// }
// const bar1 = foo("why")
// bar1() // why
// bar1() // why
// const bar2 = foo("kobe")
// bar2() // kobe
// bar1() // why
export default App;
1.7 useMemo
import React, { memo, useCallback } from "react";
import { useMemo, useState } from "react";
const HelloWorld = memo(function (props) {
console.log("HelloWorld被渲染~");
return <h2>Hello World</h2>;
});
function calcNumTotal(num) {
// console.log("calcNumTotal的计算过程被调用~")
let total = 0;
for (let i = 1; i <= num; i++) {
total += i;
}
return total;
}
const App = memo(() => {
const [count, setCount] = useState(0);
// const result = calcNumTotal(50)
// 1.不依赖任何的值, 进行计算
// 传入的是数值 只要数值没有发生变化 子组件就不会重新渲染
const result = useMemo(() => {
return calcNumTotal(50);
}, []);
// 2.依赖count
// const result = useMemo(() => {
// return calcNumTotal(count*2)
// }, [count])
// 3.useMemo和useCallback的对比
// useMemo是对值做优化 而useCallBack是对函数做优化
function fn() {}
// const increment = useCallback(fn, [])
// const increment2 = useMemo(() => fn, [])
// 4.使用useMemo对子组件渲染进行优化
// const info = { name: "why", age: 18 }
// 传入的是对象的话 APP组件重新渲染对象也会被重新创建 导致子组件也重新渲染
const info = useMemo(() => ({ name: "why", age: 18 }), []);
return (
<div>
<h2>计算结果: {result}</h2>
<h2>计数器: {count}</h2>
<button onClick={(e) => setCount(count + 1)}>+1</button>
<HelloWorld result={result} info={info} />
</div>
);
});
export default App;
1.8 useRef
1.8.1 ref绑定dom
import React, { memo, useRef } from 'react'
const App = memo(() => {
const titleRef = useRef()
const inputRef = useRef()
function showTitleDom() {
console.log(titleRef.current)
inputRef.current.focus()
}
return (
<div>
<h2 ref={titleRef}>Hello World</h2>
<input type="text" ref={inputRef} />
<button onClick={showTitleDom}>查看title的dom</button>
</div>
)
})
export default App
1.8.2 ref解决闭包缺陷
import React, { memo, useRef } from "react";
import { useCallback } from "react";
import { useState } from "react";
let obj = null;
const App = memo(() => {
const [count, setCount] = useState(0);
const nameRef = useRef();
console.log(obj === nameRef);
obj = nameRef;
// 通过useRef解决闭包陷阱
// 这里的ref使用是保持一致的 不会发生改变 所以将可以将count赋值给ref
const countRef = useRef();
countRef.current = count;
// 这里闭包产生的原因是是 第一次就创建了一个函数 count 执行之后 = 1
// 而在第二次执行的时候 依然是拿到count = 1的结果 并没有发生改变
// 为了解决这个问题就使用ref保存的数值
const increment = useCallback(() => {
setCount(countRef.current + 1);
}, []);
return (
<div>
<h2>Hello World: {count}</h2>
<button onClick={(e) => setCount(count + 1)}>+1</button>
<button onClick={increment}>+1</button>
</div>
);
});
export default App;
1.9 useImperativeHandle
import React, { memo, useRef, forwardRef, useImperativeHandle } from "react";
const HelloWorld = memo(
forwardRef((props, ref) => {
const inputRef = useRef();
// 子组件对父组件传入的ref进行处理
// 不让父组件直接拿到input的所有方法 所以将自己想要抛出去的方法包裹起来
useImperativeHandle(ref, () => {
return {
focus() {
console.log("focus");
inputRef.current.focus();
},
setValue(value) {
inputRef.current.value = value;
},
};
});
return <input type="text" ref={inputRef} />;
})
);
const App = memo(() => {
const titleRef = useRef();
const inputRef = useRef();
function handleDOM() {
// console.log(inputRef.current)
inputRef.current.focus();
// 不能直接通过.value的方法来修改 只能通过setValue的方法来修改
// inputRef.current.value = ""
inputRef.current.setValue("哈哈哈");
}
return (
<div>
<h2 ref={titleRef}>哈哈哈</h2>
<HelloWorld ref={inputRef} />
<button onClick={handleDOM}>DOM操作</button>
</div>
);
});
export default App;
1.10 useLayoutEffect
import React, { memo, useEffect, useLayoutEffect, useState } from "react";
const App = memo(() => {
const [count, setCount] = useState(100);
// 这时候已经显示到界面上 才执行修改count的数值会导致页面闪烁
// useEffect(() => {
// console.log("useEffect");
// if (count === 0) {
// setCount(Math.random() + 99);
// }
// });
useLayoutEffect(() => {
console.log("useLayoutEffect");
if (count === 0) {
setCount(Math.random() + 99);
}
});
console.log("App render");
return (
<div>
<h2>count: {count}</h2>
<button onClick={(e) => setCount(0)}>设置为0</button>
</div>
);
});
export default App;
1.11 自定义Hook
1.11.1 什么是自定义Hook
import React, { memo, useEffect, useState } from 'react'
function useLogLife(cName) {
useEffect(() => {
console.log(cName + "组件被创建")
return () => {
console.log(cName + "组件被销毁")
}
}, [cName])
}
const Home = memo(() => {
useLogLife("home")
return <h1>Home Page</h1>
})
const About = memo(() => {
useLogLife("about")
return <h1>About Page</h1>
})
const App = memo(() => {
const [isShow, setIsShow] = useState(true)
useLogLife("app")
return (
<div>
<h1>App Root Component</h1>
<button onClick={e => setIsShow(!isShow)}>切换</button>
{ isShow && <Home/> }
{ isShow && <About/> }
</div>
)
})
export default App
1.11.2 Context的共享
import { createContext } from "react";
const UserContext = createContext();
const TokenContext = createContext();
export { UserContext, TokenContext };
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<UserContext.Provider value={{ name: "why", level: 99 }}>
<TokenContext.Provider value={"coderwhy"}>
<App />
</TokenContext.Provider>
</UserContext.Provider>
);
Hook
import { useContext } from "react";
import { UserContext, TokenContext } from "../context";
function useUserToken() {
const user = useContext(UserContext);
const token = useContext(TokenContext);
return [user, token];
}
export default useUserToken;
import React, { memo } from 'react'
import { useUserToken } from "./hooks"
// User/Token
const Home = memo(() => {
const [user, token] = useUserToken()
return <h1>Home Page: {user.name}-{token}</h1>
})
const About = memo(() => {
const [user, token] = useUserToken()
return <h1>About Page: {user.name}-{token}</h1>
})
const App = memo(() => {
return (
<div>
<h1>App Root Component</h1>
<Home/>
<About/>
</div>
)
})
export default App
1.11.3 获取鼠标滚动位置
import React, { memo } from 'react'
import useScrollPosition from './hooks/useScrollPosition'
import "./style.css"
const Home = memo(() => {
const [scrollX, scrollY] = useScrollPosition()
return <h1>Home Page: {scrollX}-{scrollY}</h1>
})
const About = memo(() => {
const [scrollX, scrollY] = useScrollPosition()
return <h1>About Page: {scrollX}-{scrollY}</h1>
})
const App = memo(() => {
return (
<div className='app'>
<h1>App Root Component</h1>
<Home/>
<About/>
</div>
)
})
export default App
import { useState, useEffect } from "react";
function useScrollPosition() {
const [scrollX, setScrollX] = useState(0);
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
function handleScroll() {
// console.log(window.scrollX, window.scrollY)
// 监听到滚动就把值保存下来
setScrollX(window.scrollX);
setScrollY(window.scrollY);
}
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return [scrollX, scrollY];
}
export default useScrollPosition;
1.11.4 storage
import { useEffect } from "react";
import { useState } from "react";
function useLocalStorage(key) {
// 1.从localStorage中获取数据, 并且数据数据创建组件的state
const [data, setData] = useState(() => {
const item = localStorage.getItem(key);
if (!item) return "";
return JSON.parse(item);
});
// 2.监听data改变, 一旦发生改变就存储data最新值
useEffect(() => {
localStorage.setItem(key, JSON.stringify(data));
}, [data]);
// 3.将data/setData的操作返回给组件, 让组件可以使用和修改值
return [data, setData];
}
export default useLocalStorage;
import React, { memo } from 'react'
import { useEffect } from 'react'
import { useState } from 'react'
import useLocalStorage from './hooks/useLocalStorage'
const App = memo(() => {
// 通过key, 直接从localStorage中获取一个数据
// const [token, setToken] = useState(localStorage.getItem("token"))
// useEffect(() => {
// localStorage.setItem("token", token)
// }, [token])
const [token, setToken] = useLocalStorage("token")
function setTokenHandle() {
setToken("james")
}
// const [avatarUrl, setAvatarUrl] = useState(localStorage.getItem("avatarUrl"))
// useEffect(() => {
// localStorage.setItem("avatarUrl", avatarUrl)
// }, [avatarUrl])
const [avatarUrl, setAvatarUrl] = useLocalStorage("avatarUrl")
function setAvatarUrlHandle() {
setAvatarUrl("http://www.james.com/cba.png")
}
return (
<div className='app'>
<h1>App Root Component: {token}</h1>
<button onClick={setTokenHandle}>设置token</button>
<h1>avatarURL: {avatarUrl}</h1>
<button onClick={setAvatarUrlHandle}>设置新头像地址</button>
</div>
)
})
export default App
1.12 redux中的hook
import React, { memo } from 'react'
import { connect } from "react-redux"
import { addNumberAction, subNumberAction } from './store/modules/counter'
const App = memo((props) => {
const { count, addNumber, subNumber } = props
function addNumberHandle(num, isAdd = true) {
if (isAdd) {
addNumber(num)
} else {
subNumber(num)
}
}
return (
<div>
<h2>当前计数: {count}</h2>
<button onClick={e => addNumberHandle(1)}>+1</button>
<button onClick={e => addNumberHandle(6)}>+6</button>
<button onClick={e => addNumberHandle(6, false)}>-6</button>
</div>
)
})
const mapStateToProps = (state) => ({
count: state.counter.count
})
const mapDispatchToProps = (dispatch) => ({
addNumber(num) {
dispatch(addNumberAction(num))
},
subNumber(num) {
dispatch(subNumberAction(num))
}
})
export default connect(mapStateToProps, mapDispatchToProps)(App)
import React, { memo } from "react";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import {
addNumberAction,
changeMessageAction,
subNumberAction,
} from "./store/modules/counter";
// memo高阶组件包裹起来的组件有对应的特点: 只有props发生改变时, 才会重新渲染
// 而且useSelector监听的是state的变化 所以state变化的时候也会引起 重新渲染
// 加上shallowEqual 就只会在我们使用的参数发生变化的时候才重新渲染
const Home = memo((props) => {
const { message } = useSelector(
(state) => ({
message: state.counter.message,
}),
shallowEqual
);
// 使用dispatch 可以直接使用reducer
const dispatch = useDispatch();
function changeMessageHandle() {
dispatch(changeMessageAction("你好啊, 师姐!"));
}
console.log("Home render");
return (
<div>
<h2>Home: {message}</h2>
<button onClick={(e) => changeMessageHandle()}>修改message</button>
</div>
);
});
const App = memo((props) => {
// 1.使用useSelector将redux中store的数据映射到组件内
const { count } = useSelector(
(state) => ({
count: state.counter.count,
}),
shallowEqual
);
// 2.使用dispatch直接派发action
const dispatch = useDispatch();
function addNumberHandle(num, isAdd = true) {
if (isAdd) {
dispatch(addNumberAction(num));
} else {
dispatch(subNumberAction(num));
}
}
console.log("App render");
return (
<div>
<h2>当前计数: {count}</h2>
<button onClick={(e) => addNumberHandle(1)}>+1</button>
<button onClick={(e) => addNumberHandle(6)}>+6</button>
<button onClick={(e) => addNumberHandle(6, false)}>-6</button>
<Home />
</div>
);
});
export default App;
1.13 讲讲SPA和 Hydration
SPA页面
-
1、不利于SEO优化搜索引擎优化
-
2、首屏渲染速度慢
-
1、不利于SEO优化搜索引擎优化
-
- 例如百度页面在进行关键词收录的时候 是通过请求index.html页面而SPA应用的index.html页面是很简单的,其他资源存在bundle中,另外还有一种就是获取meta配置 meta配置也是有限的,会导致获取到关于网站的资源比较少而导致网站排名靠后
-
2、首屏渲染速度慢
-
- 网站的资源都是通过
src = 'bundle.js'
去获取 需要下载bundle.js文件 然后浏览器在执行bundle.js 再通过document.createElement
讲dom渲染到页面上 如果请求的bundle.js文件过大 就会出现首屏渲染慢的问题
- 网站的资源都是通过
1.14 useId
import React, { memo, useId, useState } from 'react'
const App = memo(() => {
const [count, setCount] = useState(0)
const id = useId()
console.log(id)
return (
<div>
<button onClick={e => setCount(count+1)}>count+1:{count}</button>
<label htmlFor={id}>
用户名:<input id={id} type="text" />
</label>
</div>
)
})
export default App
1.15 useTransition
faker 这个库可以模拟数据文章来源:https://www.toymoban.com/news/detail-830285.html
import { faker } from '@faker-js/faker';
const namesArray = []
for (let i = 0; i < 10000; i++) {
namesArray.push(faker.name.fullName())
}
export default namesArray
import React, { memo, useState, useTransition } from "react";
import namesArray from "./namesArray";
const App = memo(() => {
const [showNames, setShowNames] = useState(namesArray);
// pending startTransition 函数执行的状态
const [pending, startTransition] = useTransition();
function valueChangeHandle(event) {
// 是在其他执行完成之后 在执行这里的函数
startTransition(() => {
const keyword = event.target.value;
const filterShowNames = namesArray.filter((item) =>
item.includes(keyword)
);
setShowNames(filterShowNames);
});
}
return (
<div>
<input type="text" onInput={valueChangeHandle} />
<h2>用户名列表: {pending && <span>data loading</span>} </h2>
<ul>
{showNames.map((item, index) => {
return <li key={index}>{item}</li>;
})}
</ul>
</div>
);
});
export default App;
1.16 useDeferredValue
文章来源地址https://www.toymoban.com/news/detail-830285.html
import React, { memo, useState, useDeferredValue } from "react";
import namesArray from "./namesArray";
const App = memo(() => {
const [showNames, setShowNames] = useState(namesArray);
// 跟useTransition的作用差不多 是对数据做处理而transition是对函数做处理
const deferedShowNames = useDeferredValue(showNames);
function valueChangeHandle(event) {
const keyword = event.target.value;
const filterShowNames = namesArray.filter((item) => item.includes(keyword));
setShowNames(filterShowNames);
}
return (
<div>
<input type="text" onInput={valueChangeHandle} />
<h2>用户名列表: </h2>
<ul>
{deferedShowNames.map((item, index) => {
return <li key={index}>{item}</li>;
})}
</ul>
</div>
);
});
export default App;
到了这里,关于react 【七】各种hooks的使用/SPA的缺点的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!