初级:React 中的生命周期方法和 Hook
原创react hooks 彻底改变了我们在 react 中编写功能组件的方式,使我们无需编写类即可使用状态和其他 react 功能。本指南将向您介绍基本的钩子、自定义钩子和高级钩子模式,以管理复杂的状态并优化性能。
react hook 简介
react hooks 是让您从功能组件“挂钩”react 状态和生命周期功能的函数。 hooks 是在 react 16.8 中引入的,它们提供了一种更直接的方式在功能组件中使用状态和其他 react 功能。
hooks 的主要优点
- 更简单的代码: hooks 允许您直接在功能组件中使用状态和生命周期方法,从而使代码更简单、更具可读性。
- 重用逻辑:自定义挂钩使您能够跨多个组件提取和重用有状态逻辑。
- 增强的功能组件: hooks 提供了类组件的所有功能,例如管理状态和副作用,而无需使用类。
必备挂钩
使用状态
usestate 是一个钩子,允许您向功能组件添加状态。
示例:
import react, { usestate } from 'react'; const counter = () => { const [count, setcount] = usestate(0); return ( <div> <p>you clicked {count} times</p> <button onclick="{()"> setcount(count + 1)}>click me</button> </div> ); }; export default counter;
在此示例中,usestate 将 count 状态变量初始化为 0。setcount 函数在单击按钮时更新状态。
使用效果
useeffect 是一个钩子,可让您在功能组件中执行副作用,例如获取数据、直接与 dom 交互以及设置订阅。它结合了类组件中多个生命周期方法的功能(componentdidmount、componentdidupdate 和 componentwillunmount)。
示例:
import react, { usestate, useeffect } from 'react'; const datafetcher = () => { const [data, setdata] = usestate(null); useeffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setdata(data)); }, []); return ( <div> {data ? <pre class="brush:php;toolbar:false">{json.stringify(data, null, 2)}: 'loading...'} ); }; export default datafetcher;
在此示例中,useeffect 在组件挂载时从 api 获取数据。
使用上下文
usecontext 是一个钩子,可让您访问给定上下文的上下文值。
示例:
import react, { usecontext } from 'react'; const themecontext = react.createcontext('light'); const themedcomponent = () => { const theme = usecontext(themecontext); return <div>the current theme is {theme}</div>; }; export default themedcomponent;
在此示例中,usecontext 访问 themecontext 的当前值。
使用reducer
usereducer 是一个钩子,可让您管理功能组件中的复杂状态逻辑。它是 usestate 的替代品。
示例:
import react, { usereducer } from 'react'; const initialstate = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const counter = () => { const [state, dispatch] = usereducer(reducer, initialstate); return ( <div> <p>count: {state.count}</p> <button onclick="{()"> dispatch({ type: 'increment' })}>increment</button> <button onclick="{()"> dispatch({ type: 'decrement' })}>decrement</button> </div> ); }; export default counter;
在这个例子中,usereducer通过reducer函数来管理计数状态。
定制挂钩
自定义挂钩让您可以跨多个组件重用有状态逻辑。自定义钩子是使用内置钩子的函数。
示例:
import { usestate, useeffect } from 'react'; const usefetch = (url) => { const [data, setdata] = usestate(null); useeffect(() => { fetch(url) .then(response => response.json()) .then(data => setdata(data)); }, [url]); return data; }; const datafetcher = ({ url }) => { const data = usefetch(url); return ( <div> {data ? <pre class="brush:php;toolbar:false">{json.stringify(data, null, 2)}: 'loading...'}