React hooks
27003 단어 react.
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 hook
React 구성 요소 에서 데 이 터 를 가 져 오 거나 구독 하거나 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.
에서 만 호출hooks
3.hooks 는 render 호출 할 때마다 마지막 호출 순서 에 대응 합 니 다.조건문 에 넣 으 면 한 번 실행 하지 않 으 면 원래 의 순 서 를 흐 트 러 뜨 려 뒤의 hooks 를 현재 hooks 에 대응 합 니 다.customs hooks
사용자 정의 hooks 는 function 이름 을
use
로 시작 하고 일부 공용 논 리 를 이 방법 에 넣 고React
로 정의 하 는hooks
를 사용 하 는 것 을 말 합 니 다.고급 구성 요소 와 유사 합 니 다render props
.주의 가 필요 할 때
customs hooks
재 활용 은logic
이 고,매번 사용 할 때마다state、effect
등hooks
은 새것 이다.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>
</>
);
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
nginx 에서 사이트 아이콘 표시 설정전단 개발 환경: react:^16.4.1 webpack:^4.16.0 웹 팩 에 favicon. ico 설정 추가: nginx 는 ico 에 대한 지원 을 추가 합 니 다:...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.