react的钩子
原链接:https://www.ruanyifeng.com/blog/2019/09/react-hooks.html
状态的钩子(useState() )
import React, { useState } from "react";
let [bannner,setBanner] = useState()
setsetBanner(1)
console.log(bannner) //1
共享状态钩子 (useContext() )
<div className="App">
<Navbar/>
<Messages/>
</div>
//第一步就是使用 React Context API,在组件外部建立一个 Context。
const AppContext = React.createContext({});
<AppContext.Provider value={{
username: 'superawesome'
}}>
<div className="App">
<Navbar/>
<Messages/>
</div>
</AppContext.Provider>
//上面代码中,AppContext.Provider提供了一个 Context 对象,这个对象可以被子组件共享。
const Navbar = () => {
const { username } = useContext(AppContext);
return (
<div className="navbar">
<p>AwesomeSite</p>
<p>{username}</p>
</div>
);
}
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>
)
}
action 钩子 (useReducer() )
//React 本身不提供状态管理功能,通常需要使用外部库。这方面最常用的库是 Redux。
//Redux 的核心概念是,组件发出 action 与状态管理器通信。状态管理器收到 action 以后,使用 Reducer 函数//算出新的状态,Reducer 函数的形式是(state, action) => newState。
const [state, dispatch] = useReducer(reducer, initialState);
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>
);
}
副作用钩子 (useEffect())
https://www.ruanyifeng.com/blog/2020/09/react-hooks-useeffect-tutorial.html
//useEffect()用来引入具有副作用的操作,最常见的就是向服务器请求数据。以前,放在componentDidMount里面的代码,现在可以放在useEffect()。
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>
}