react-Hook
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <App />, document.querySelector('#app') )
App.js
import React from 'react'; import Home from './Home'; export default class extends React.Component { render () { return ( <div> <Home /> </div> ) } }
组件
Home.js (count.js)
import React, { useState } from 'react'; const Home = () => { // 声明一个新的叫做 “count” 的 state 变量 // 设置初始化数据为0, 改变count的函数为setCount const [ count, setCount ] = useState(0) const [ list, setList ] = useState([1, 2, 3, 4]) return ( <div> <button onClick= { () => { let num = count + 1 setCount(num) }}>加1</button> { count } <button onClick= { () => { setList([5,6,7,8]) }}>改变list</button> { list.map((item, index) => ( <p key = { index }> { item } </p> )) } </div> ) } export default Home;
Home.js (Home-useEffect.js)
import React, { useState, useEffect } from 'react'; import axios from 'axios'; // useEffect 其实是 componentDidMount + componentDidUpdate + componentWillUnmount const Home = () => { const [ bannerlist, setBannerlist ] = useState([]) useEffect(() => { axios.get('/api/banner').then(res => { setBannerlist(res.data.data) // console.log(bannerlist) }) }) const [ prolist, setProlist ] = useState([]) useEffect(() => { axios.get('/api/pro').then(res => { setProlist(res.data.data) }) }) return ( <div> 轮播图列表 { bannerlist.map(item => ( <p key = { item.bannerid }> { item.img } </p> )) } { prolist.map(item => ( <p key = { item.proid }> { item.proname } </p> )) } </div> ) } export default Home;
Home.js (Home-useEffect控制.js)
import React, { useState, useEffect } from 'react'; import axios from 'axios'; // useEffect 其实是 componentDidMount + componentDidUpdate + componentWillUnmount const Home = () => { const [ bannerlist, setBannerlist ] = useState([]) useEffect(() => { axios.get('/api/banner').then(res => { setBannerlist(res.data.data) // console.log(bannerlist) }) }, [bannerlist]) // 比较2次相同即跳过 const [ prolist, setProlist ] = useState([]) useEffect(() => { axios.get('/api/pro').then(res => { setProlist(res.data.data) }) }, []) // 执行只运行一次的 effect return ( <div> 轮播图列表 { bannerlist.map(item => ( <p key = { item.bannerid }> { item.img } </p> )) } { prolist.map(item => ( <p key = { item.proid }> { item.proname } </p> )) } </div> ) } export default Home;
Home.js
import React, { useState, useEffect } from 'react'; import axios from 'axios'; // 自定义HOOK const useLoginState = () => { const [loginstate, setLoginstat] = useState('no') useEffect(() => { if (localStorage.getItem('loginstate') === 'ok') { setLoginstat('ok') } else { setLoginstat('no') } }, [loginstate]) return loginstate } const Home = () => { const loginstate = useLoginState() return ( <div> 自定义HOOK { loginstate === 'ok' ? <p>登陆了</p> : <p>未登录</p> } </div> ) } export default Home;
长风破浪会有时,直挂云帆济沧海