Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

react-hooks.pdf

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
How do we use hooks
How do we use hooks
Wird geladen in …3
×

Hier ansehen

1 von 47 Anzeige

Weitere Verwandte Inhalte

Ähnlich wie react-hooks.pdf (20)

Aktuellste (20)

Anzeige

react-hooks.pdf

  1. 1. THE NEXT GENERATION THE NEXT GENERATION OF REACT - HOOKS OF REACT - HOOKS
  2. 2. SELF-INTRODUCTION SELF-INTRODUCTION Ef ciency and Service - Tech Lead ChengBo Xu
  3. 3. OUTLINE OUTLINE Why React hooks React rooks introduction From class component to functional component and react hooks The practice of React Hooks
  4. 4. WHY REACT HOOKS WHY REACT HOOKS
  5. 5. TO REUSE LOGIC BETWEEN COMPONENTS TO REUSE LOGIC BETWEEN COMPONENTS
  6. 6. THE PROBLEMS OF HOC THE PROBLEMS OF HOC
  7. 7. THE PROBLEMS OF HOC THE PROBLEMS OF HOC Change Component name
  8. 8. THE PROBLEMS OF HOC THE PROBLEMS OF HOC Change Component name Add component hierarchy
  9. 9. THE PROBLEMS OF HOC THE PROBLEMS OF HOC Change Component name Add component hierarchy More maintenance cost(component will spit to component itself and wrapperComponent)
  10. 10. RENDERPROPS(FACC - FUNCTION AS CHILD COMPONENT) RENDERPROPS(FACC - FUNCTION AS CHILD COMPONENT) const MyContext = React.createContext(defaultValue); <MyContext.Provider value={/* some value */}> <MyContext.Consumer> {value => /* render something based on the context value */} </MyContext.Consumer>
  11. 11. THE PROBLEM OF FACC THE PROBLEM OF FACC “There are only two hard things in Computer Science: cache invalidation and naming things.” – Popularly attributed to Phil Karlton
  12. 12. CLASS COMPONENT CLASS COMPONENT
  13. 13. @connect(mapStateToProps) class Projects extends Component { static propTypes = { list: array.isRequired, loading: object.isRequired, type: string, }; static defaultProps = { type: '', }; componentDidMount() { this.fetchProjects(); }
  14. 14. THE PROBLEMS OF CLASS THE PROBLEMS OF CLASS
  15. 15. THE PROBLEMS OF CLASS THE PROBLEMS OF CLASS Is "this" really necessary?
  16. 16. THE PROBLEMS OF CLASS THE PROBLEMS OF CLASS Is "this" really necessary? The instance function must bind "this"
  17. 17. THE PROBLEMS OF CLASS THE PROBLEMS OF CLASS Is "this" really necessary? The instance function must bind "this" Too much outside logic in component lifecycle: didMount/willRecieveProps/didupdate
  18. 18. THE PROBLEMS OF CLASS THE PROBLEMS OF CLASS Is "this" really necessary? The instance function must bind "this" Too much outside logic in component lifecycle: didMount/willRecieveProps/didupdate Class is not friendly to code optimization
  19. 19. REACT ROOKS INTRODUCTION REACT ROOKS INTRODUCTION
  20. 20. WHAT IS REACT HOOKS WHAT IS REACT HOOKS
  21. 21. WHAT IS REACT HOOKS WHAT IS REACT HOOKS Function
  22. 22. BUILT-IN HOOKS BUILT-IN HOOKS useState useEffect/useLayoutEffect useCallback useMemo useContext useRef useReducer useImperativeHandle useDebugValue
  23. 23. useState const [state, setState] = useState(initialState);
  24. 24. function Counter({initialCount}) { const [count, setCount] = useState(initialCount); return ( <> Count: {count} <button onClick={() => setCount(initialCount)}>Reset</butto <button onClick={() => setCount(prevCount => prevCount + 1) <button onClick={() => setCount(prevCount => prevCount - 1) </> ); }
  25. 25. useEffect/useLayoutEffect useEffect(didUpdate,[a]);
  26. 26. useEffect(() => { const subscription = props.observable.subscribe(observer); return () => { // Clean up the subscription subscription.unsubscribe(); }; },[props.observable]);
  27. 27. useContext const context = useContext(Context);
  28. 28. import { useContext } from 'react'; import { ReactReduxContext } from 'react-redux'; const useDispatch = () => { const context = useContext(ReactReduxContext); return context.store.dispatch; }; export default useDispatch;
  29. 29. useCallback const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], );
  30. 30. function App(){ const handler = useCallback((e)=>{ e.preventDefault(); alert('clicked') }); return ( <Dropdown onDropDown={handler} /> ) }
  31. 31. useMemo const memoizedValue = useMemo(() => compute(a, b), [a, b]);
  32. 32. useRef function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
  33. 33. useImperativeHandle useImperativeHandle(ref, createHandle, [inputs])
  34. 34. useDebugValue useDebugValue(value)
  35. 35. THE RULES OF HOOKS THE RULES OF HOOKS Hooks can only be called at the top level of a React function component. cannot be called inside a function method. cannot be called in condition block. cannot be called in loop block. Hooks can be called inside custom react hooks. Separate component dependencies and component UI*
  36. 36. SEPARATE COMPONENT DEPENDENCIES AND COMPONENT SEPARATE COMPONENT DEPENDENCIES AND COMPONENT UI UI const CreateMarkTaskModal: FunctionComponent<Props> = props => { const { onSubmit, visible, ...rest } = props; const [datasetList, updatedAtasetList] = useState<StateList>([] const [initialized, updateInitialized] = useState<boolean>(fals const [tagsetData, updateTagsetData] = useState<StateList>([]); const [versionList, updateVersionList] = useState<StateList>([] const [isFetchingTagset, fetchTagset] = usePromisifyObservable<u () => listAllTagsets(), data => updateTagsetData(data.map(({ name }) => name)), ); const [isFetchingDatalist, fetchDataList] = usePromisifyObservab () => listDataset(), response => updatedAtasetList(response.map(({ name }) => name );
  37. 37. FROM CLASS COMPONENT TO FUNCTION FROM CLASS COMPONENT TO FUNCTION COMPONENT COMPONENT Constructor useState getDerivedStateFromProps shouldComponentUpdate useCallback useMemo Probably Don't Need It
  38. 38. componentDidMount componentDidUpdate componentWillUnmount useEffect componentDidCatch getDerivedStateFromError getSnapshotBeforeUpdate no Hooks
  39. 39. THE PRACTICE IN REACTHOOKS THE PRACTICE IN REACTHOOKS
  40. 40. useEffect function useDocumentTitle(title) { useEffect( () => { document.title = title; return () => (document.title = "默认标题"); }, [title] ); }
  41. 41. usePromsie function usePromise(promiseConst){ const [isResoving, updateResolving] = useState(false); const executer = useCallback(() => { updateResolving(true); return new Promise(promiseConst).finally(()=> updateResolvi },[promiseConst]) return [isResoving, executer]; }
  42. 42. useInputChange function useInputChange(init = ''){ const [value, updateValue] = useState(init); const onChange = useCallback((e)=>{ updateValue(e.target.value); },[]) return [value, onChange]; } function HelloName(){ let [name, onChange] = useInputChange('james'); return ( <> <div>hello {name}</div>
  43. 43. useLocalStorage function useLocalStorage(key){ const [item, updateItem] = useState(()=> localStorage.getItem(k const setItem = useCallback((value)=>{ updateValue(value); localStorage.setItem(key); },[key]); return [item, setItem] } function App (){ const [name, setItem] = useLocalStorage('name'); const changeHandler = useCallback((e)=>{
  44. 44. RECAP RECAP Hooks is function. Hooks split components into multiple Code Blocks, allowing smaller-grained logic to reuse and improve performance. "This" in the React Class component is useless in most scenarios. Most of the logic of React Class components can be simulated by Hooks. The rules of Hooks. 1. Hooks can only be called top level of React function components.
  45. 45. 2. Hooks can be called by custom hooks. 3. Separate component dependencies and component UI.*
  46. 46. Q & A Q & A

×