React hooks

27003 단어 react.
hooks 역할function component에서 hooks,예 를 들 어useState、useContext등 을 사용 하여class만 가지 고 있 는 특성 을 가지 게 할 수 있다.또한class에 서 는hooks쓸모 가 없 기 때문에 사용 할 수 없다.
useState state hooks
import React, { useState } from 'react';

function Example(props) {
  // useState     :                ,            ,      class    state       object。         。
  const [count, setCount] = useState(0/* initial state*/);
  //       ,     state,         。
  const [person, upPerson] = useState({ name: 'longjicnen', age: 21}/* initial state*/);
  return (
  <div>
  	<button onClick={() => this.setState(count + 1 )}>
    Click me
  	</button>
  	<button onClick={() => this.setState({ age: person.age + 1 })}>
    Click me
  	</button>
  </div>
  )
}

useEffect effect hookReact 구성 요소 에서 데 이 터 를 가 져 오 거나 구독 하거나 DOM 을 수 동 으로 변경 합 니 다.우 리 는 이 수술 들 을'side effect'라 고 부른다.
그것 의 역할 은 React 류 의componentDidMount、componentDidUpdate、componentWillUnmount와 마찬가지 로 그들의 집합 이다.호출useEffect할 때 기본 값 은 업데이트 할 때마다 호출effect합 니 다.첫 번 째render를 포함 합 니 다.
React 구성 요소 에는 두 가지 흔히 볼 수 있 는 부작용 이 있 습 니 다.청소 할 필요 가 없 는 부작용 과 청소 해 야 할 부작용 입 니 다.
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  //          render        ,          ,     javascript   ,         effect   。effect                。
  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    document.title = `You clicked ${count} times`;
    return () => {
		//           ,      render   unmount      ,                 。         unmount   。
	}
	//        effect,          ,                 ,               。
	useEffect(() => {
    	// featch data
  	});
	useEffect(() => {
    	// featch data
  	}, [count/*          ,       ,        re-render    effect,         ,          render     ,           effect,     [],       mount and unmount     ,      effect  , props    states            。*/]);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

rules of hooks
1.항상function component상단 에서 호출hooks하고 순환,조건 또는 내장 함수 에서 갈 고 리 를 호출 하지 마 십시오.2.function components.에서 만 호출hooks3.hooks 는 render 호출 할 때마다 마지막 호출 순서 에 대응 합 니 다.조건문 에 넣 으 면 한 번 실행 하지 않 으 면 원래 의 순 서 를 흐 트 러 뜨 려 뒤의 hooks 를 현재 hooks 에 대응 합 니 다.
customs hooks
사용자 정의 hooks 는 function 이름 을use로 시작 하고 일부 공용 논 리 를 이 방법 에 넣 고React로 정의 하 는hooks를 사용 하 는 것 을 말 합 니 다.고급 구성 요소 와 유사 합 니 다render props.
주의 가 필요 할 때customs hooks재 활용 은logic이 고,매번 사용 할 때마다state、effecthooks은 새것 이다.
import React, { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);

  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

useContext
//      MyContext     ,          ,        useContext      ,  context
const MyContext = React.createContext()
//          context.provider       ,     。        ,                 rerender
const value = useContext(MyContext);

userReducer
const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState, init/*        ,         init(initialArg) */);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

useCallback
하나 되 돌려 주기callback
//                  memoizedCallback       。   callback         ,            。
const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);

usememo value와 유사 한 계산 속성 을 되 돌려 줍 니 다.
//            []       ,     render        。
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

useRef
const refContainer/*refContainer.current  initalValue*/ = useRef(initialValue);

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>
    </>
  );
}

좋은 웹페이지 즐겨찾기