hook的出现就是为了解决函数式组件中实现class组件的很多特性,它可以让我们在不编写class的情况下使用state以及其他的React特性;
注意:
import { memo, useState } from "react";
// 普通的函数, 里面不能使用hooks
// 在自定义的hooks中, 可以使用react提供的其他hooks: 必须使用use开头
// function useFoo() {
// const [ message ] = useState("Hello World")
// return message
// }
function CounterHook(props) {
const [counter, setCounter] = useState(0)
const [name] = useState("why")
console.log(name)
// const message = useFoo()
return (
当前计数: {counter}
)
}
useEffect的解析:
清除Effect:
// 负责告知react, 在执行完当前组件渲染之后要执行的副作用代码
useEffect(() => {
// 1.监听事件
// const unubscribe = store.subscribe(() => {
// })
// function foo() {
// }
// 返回值: 回调函数 => 组件被重新渲染或者组件卸载的时候执行
return () => {
}
})
useEffect的解决方式:
useEffect(() => {
console.log("修改title:", count)
}, [count])
useEffect(() => {
console.log("监听redux中的数据")
return () => {}
}, [])
useEffect(() => {
console.log("监听eventBus的why事件")
return () => {}
}, [])
useEffect(() => {
console.log("发送网络请求, 从服务器获取数据")
return () => {
console.log("会在组件被卸载时, 才会执行一次")
}
}, [])
在开发中,要在组件中使用共享的Context有两种方式:
contxt.js
import { createContext } from "react";
const UserContext = createContext()
const ThemeContext = createContext()
export {
UserContext,
ThemeContext
}
App.jsx
import React, { memo, useContext } from 'react'
import { UserContext, ThemeContext } from "./context"
const App = memo(() => {
// 使用Context
const user = useContext(UserContext)
const theme = useContext(ThemeContext)
return (
User: {user.name}-{user.level}
Theme
)
})
export default App
import React, { memo, useReducer } from 'react'
function reducer(state, action) {
switch(action.type) {
case "increment":
return { ...state, counter: state.counter + 1 }
case "decrement":
return { ...state, counter: state.counter - 1 }
case "add_number":
return { ...state, counter: state.counter + action.num }
case "sub_number":
return { ...state, counter: state.counter - action.num }
default:
return state
}
}
const App = memo(() => {
const [state, dispatch] = useReducer(reducer, { counter: 0, friends: [], user: {} })
return (
当前计数: {state.counter}
)
})
export default App
import React, { memo, useRef } from 'react'
const App = memo(() => {
const titleRef = useRef()
const inputRef = useRef()
function showTitleDom() {
console.log(titleRef.current)
inputRef.current.focus()
}
return (
Hello World
)
})
export default App