参考文档:http://www.ruanyifeng.com/blog/2019/09/react-hooks.html
react在线编辑器:https://codesandbox.io/s/funny-forest-ncv8b
1、useState
import React, { useState } from "react"; export default function Button() { const [buttonText, setButtonText] = useState("Click me, please"); function handleClick() { return setButtonText("Thanks, been clicked!"); } return <button onClick={handleClick}>{buttonText}</button>; }
2、useEffect
useEffect(() => { // Async Action }, [dependencies]) //下面是个demo const Person = ({ personId }) => { const [loading, setLoading] = useState(true); const [person, setPerson] = useState({}); useEffect(() => { setLoading(true); fetch(`https://swapi.co/api/people/${personId}/`) .then(response => response.json()) .then(data => { setPerson(data); setLoading(false); }); }, [personId]) if (loading === true) { return <p>Loading ...</p> } return <div> <p>You're viewing: {person.name}</p> <p>Height: {person.height}</p> <p>Mass: {person.mass}</p> </div> }
3、useContext
//初步就是使用React Context API,在组件外部建立一个Context。 const AppContext = React.createContext({}); //组件封装代码如下。 <AppContext.Provider value={{ username: 'superawesome' }}> <div className="App"> <Navbar/> <Messages/> </div> </AppContext.Provider> //Navbar组件的代码如下。 const Navbar = () => { const { username } = useContext(AppContext); return ( <div className="navbar"> <p>AwesomeSite</p> <p>{username}</p> </div> ); } //顶部代码中,useContext()钩子函数用来重新发布上下文对象,从中获取username属性。 消息组件的代码也类似。 const Messages = () => { const { username } = useContext(AppContext) return ( <div className="messages"> <h1>Messages</h1> <p>1 message for {username}</p> <p className="message">useContext is awesome!</p> </div> ) }
4、useReducer
//下面是一个计数器的例子。用于计算状态的Reducer函数如下。 const myReducer = (state, action) => { switch(action.type) { case('countUp'): return { ...state, count: state.count + 1 } default: return state; } } //组件代码如下。 function App() { const [state, dispatch] = useReducer(myReducer, { count: 0 }); return ( <div className="App"> <button onClick={() => dispatch({ type: 'countUp' })}> +1 </button> <p>Count: {state.count}</p> </div> ); }
由于Hooks可以提供共享状态和Reducer函数,所以它在这些方面可以取代Redux。但是,它没法提供中间件(middleware)和时间旅行(time travel),如果你需要这两个功能,还是要用Redux 。