React框架中钩子的用法

React hooks

1. 动机

解决了组件之间复用状态逻辑的问题

由providers,consumers,高阶组件,render props等其他抽象层组成的组件会形成“嵌套地狱”
hook
useState
useEffect

2. Rules

3. Replace component lifecycle with hooks

componentDidMount: Run after the component has been rendered to the DOM.

The empty array tells to React the effect doesn't depend on any values from props or state, so useEffect will run only once after the component is created.

// With componentDidMount()
componentDidMount() {
    console.log('Hello World');
}

// with useEffect()
useEffect(() => {
    console.log('Hello World');
}, [])

componentDidUpdate: Invoked immediately after updating occurs.

We pass the previous props to the array, so useEffect will run only if the value change.

// With componentDidUpdate()
componentDidUpdate(prevProps) {
    console.log(`Hello World ${prevProps}`);
}

// with useEffect()
useEffect(() => {
    console.log('Hello World');
}, [prevProps])

componentWillUnmount: called immediately before a component is unmounted and desdroyed (cleanup purpose).

useEffect will run before the component unmounting by returning an anonymous function.

// With ccomponentDidUnmount()
componentWillUnmount() {
    console.log('Hello World');
}

// with useEffect()
useEffect(() => {
    console.log('Hello World');
    return () => {
        console.log('Do some cleanup');
    }
}, [])

4. Custom hook


Redux hooks

1. Introduction

useSelector: read state
useDispatch: redux actions, e.g. update states

2. Replace redux component with hooks

  1. refactor class component to functional component

  2. reading state with hooks: from mapStateToProps to useSelector

const ui = useSelector(state => state.ui);
export default connect(
  null,
  { toggleSwitch }
)(Toggle);
  1. redux actions: useDispatch
const dispatch = useDispatch();
// call the dispatch function with the type constant `TOGGLE`
export const TOGGLE = "ui/toggle";
// pass the payload to the dispatcher
dispatch({ type: TOGGLE, payload: 'My payload' })

References

https://medium.com/better-programming/demystifying-react-hooks-a0b56a6254c2

https://itnext.io/how-to-use-redux-with-react-hooks-5422a7ceae6e
https://codesandbox.io/s/react-redux-hook-by-indrek-lasn-utc6h?source=post_page-----5422a7ceae6e----------------------

https://codeburst.io/how-to-fetch-data-from-an-api-with-react-hooks-9e7202b8afcd

https://dev.to/ibrahima92/how-to-replace-component-lifecycle-with-useeffect-hook-in-react-2f9i

你可能感兴趣的:(React框架中钩子的用法)