实习生级别:React 中的生命周期方法和 Hooks
原创react hook 简介
react hooks 是允许您在功能组件中使用状态和其他 react 功能的函数。在钩子之前,状态逻辑仅在类组件中可用。 hooks 为您已经了解的 react 概念提供了更直接的 api,例如状态、生命周期方法和上下文。
react 中的关键 hook
使用状态
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...'}