useState와 useEffect의 차이점은 무엇입니까?
react v16에서 소개된 이 두 가지 새로운 개념을 보았습니다.
내가 아는 바로는:
useState비슷해setState과 훅이useEffect라이프 사이클 방법처럼 작동합니다.
가가이 해해 ??? ???그렇지 않은 경우, 정확한 차이는 무엇입니까?useState ★★★★★★★★★★★★★★★★★」useEffect
말하면, 둘 다입니다.useState ★★★★★★★★★★★★★★★★★」useEffect기능 컴포넌트를 강화하여 클래스에서는 실행할 수 있지만 기능 컴포넌트(후크 없음)에서는 실행할 수 없는 작업을 수행합니다.
useState기능 컴포넌트가 다음과 같은 상태를 가질 수 있습니다.this.state이치노useEffect기능 컴포넌트에 라이프 사이클 방법(예:componentDidMount,componentDidUpdate★★★★★★★★★★★★★★★★★」componentWillUnmount의 API로
상세한 것에 대하여는, 다음의 예를 참조해 주세요.
useState
class CounterClass extends React.Component {
constructor(props) {
super(props);
this.state = { count: 1 };
}
render() {
return <div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({
count: this.state.count + 1
})}>Increase</button>
</div>;
}
}
function CounterFunction() {
const [count, setCount] = React.useState(1);
return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}
>Increase</button>
</div>
);
}
ReactDOM.render(
<div>
<CounterClass />
<CounterFunction />
</div>
, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
useEffect
class LifecycleClass extends React.Component {
componentDidMount() {
console.log('Mounted');
}
componentWillUnmount() {
console.log('Will unmount');
}
render() {
return <div>Lifecycle Class</div>;
}
}
function LifecycleFunction() {
React.useEffect(() => {
console.log('Mounted');
return () => {
console.log('Will unmount');
};
}, []); // Empty array means to only run once on mount.
return (
<div>Lifecycle Function</div>
);
}
ReactDOM.render(
<div>
<LifecycleClass />
<LifecycleFunction />
</div>
, document.querySelector('#app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
공식 React 문서에 대한 useState 및 useEffect에 대한 자세한 내용은 여기를 참조하십시오.
★★★의 useState()
첫째, 지원되지 않는 기능 컴포넌트가 있습니다.state즉, 기능 컴포넌트는 스테이트리스 컴포넌트입니다.
이제 Hooks를 사용하면 기능적인 컴포넌트를 사용할 수 있지만 스테이트풀한 컴포넌트를 사용할 수 있습니다.useState를 사용하면 됩니다.
★★★의 useEffect()
첫째, 스테이트리스 기능 컴포넌트에서는 컴포넌트 라이프 사이클 훅이 없었습니다.즉, 구성 요소 수명 주기 후크를 사용하려면 항상 클래스 구성 요소의 사용을 고려해야 합니다.
클래스 컴포넌트를 사용하지 않고 컴포넌트 라이프 사이클 훅을 사용할 수 있게 되었습니다.useEffect를 사용하면 됩니다.즉, 컴포넌트의 라이프 사이클 훅을 사용하고 싶을 때는 클래스 컴포넌트를 사용하는 경우와 Hooks를 사용하는 경우의 2가지 옵션이 있습니다.useEffect.
갱신하다
이 있을까요?
useState★★★★★★★★★★★★★★★★★」useEffect
로 말하면, 마로로 in in in in in in in in in in.useState스테이트리스였던 기능 컴포넌트를 스테이트풀하게 할 수 있습니다.그리고.useEffect에서는 기능 컴포넌트가 이전에는 클래스 컴포넌트에서만 지원되던 컴포넌트 라이프 사이클 훅을 활용할 수 있습니다.
useState ★★★★★★★★★★★★★★★★★」useEffect 16.훅 생태계의 이 생태계는 를 클래스 할 수 하는 것을 으로 하고 있습니다(React 16.8+ 훅 ).이 생태계는 기능 컴포넌트를 클래스 베이스 컴포넌트에서만 사용할 수 있던 기능과 동일한 기능을 제공하는 것을 목적으로 하고 있습니다(statesetState: "Component Life Cycle Method")componentDidMount,componentDidUpdate , , , , 입니다.componentWillUnmount)
useState()에서는 동작하는 컴포넌트 내에 스테이트액세서를 설치할 수 있습니다.
useEffect()할 수 있다componentDidMount,componentDidUpdate , , , , 입니다.componentWillUnmount지지롭롭롭롭롭롭
여기서 논의해야 할 대부분의 내용은 공식 문서에서 해독할 수 있습니다.텍스트로 추론하는 것보다 직장에서 후크를 보는 것이 더 쉽다.
렌더 전 라이프 사이클
렌더 전 라이프 사이클 이벤트와 동등componentWillReceiveProps ★★★★★★★★★★★★★★★★★」getDerivedStateFromProps ★★★★★★★★★★★★★★★★★」componentWillMount에서 JSX(react-node)를일 수 는 JSX와하기 때문입니다.render(…)클래스 기반 컴포넌트의 메서드.
렌더 전 라이프 사이클 이벤트를 처리하는 후크는 필요 없습니다.
렌더 후의 라이프 사이클
렌더 후 라이프 사이클 이벤트(이에 상당하는 이벤트)componentDidMount,componentDidUpdate ★★★★★★★★★★★★★★★★★」componentDidUnmount이치노
이들 메인 컴포넌트 함수가 JSX(**_useEffect(…)_**반응 노드)를 반환한 후에 실행해야 하기 때문에 메인 컴포넌트 함수에 이들 라이프 사이클이벤트에 연결된 로직을 쓸 수 없기 때문에 **렌더 후 라이프 사이클이벤트를 처리할 필요가 있습니다**react-dom렌더러
갈고리로 할 수 있는 게 많다는 뜻이죠. 어떻게요?
는 알고 있습니다.useEffect(fn, […watchStates])2번입니다.
fn( : (필수)useEffect는 (2)으로 모든 에 이 으로 실행되도록 합니다. ★★fnun-n-no-no-no-no-no-no-no-no-no-no-no-no-no-no-no-no-no-no-nto-no-no-no-no-no-n'를 반환할 수[…watchValues ]( : (예:)useEffect이 마지막 사이클에서 을 받는 은 " 사이클"뿐입니다.fn않으면 사이클마다 .이 인수를 지정하지 않으면 효과가 모든 렌더링 사이클에서 실행됩니다.
(2)의논거를 다 같이, 이 경우 (2)의 .fn모든 렌더링 사이클 후에 호출됩니다.
가 있는 값이 된 (2)하고 (2)의 변경을 감시할 필요가 있는 에는 (2)를 합니다.fn꽤 자기 설명적인 변화죠
은 빈 배열을 하는 것입니다.[]2)의으로서 (2)의할 수 .fn 때문에 이 후속 렌더 에 "Render-Cycle"이합니다.fn
import React, { useState, useEffect } from "react";
export default props => {
console.log("componentWillMount");
console.log("componentWillReceiveProps", props);
const [x, setX] = useState(0);
const [y, setY] = useState(0);
const [moveCount, setMoveCount] = useState(0);
const [cross, setCross] = useState(0);
const mouseMoveHandler = event => {
setX(event.clientX);
setY(event.clientY);
};
useEffect(() => {
console.log("componentDidMount");
document.addEventListener("mousemove", mouseMoveHandler);
return () => {
console.log("componentDidUnmount");
document.removeEventListener("mousemove", mouseMoveHandler);
};
}, []); // empty-array means don't watch for any updates
useEffect(
() => {
// if (componentDidUpdate & (x or y changed))
setMoveCount(moveCount + 1);
},
[x, y]
);
useEffect(() => {
// if componentDidUpdate
if (x === y) {
setCross(x);
}
});
return (
<div>
<p style={{ color: props.color }}>
Your mouse is at {x}, {y} position.
</p>
<p>Your mouse has moved {moveCount} times</p>
<p>
X and Y positions were last equal at {cross}, {cross}
</p>
</div>
);
};
코드 스니펫은 단순하고 자기 설명적입니다.코드펜에서 시험해 볼 수 있어요.
한 가지 중요한 점은 효과 내에서 상태를 변경하는 경우 내부에서 변경되는 상태를 워치 배열에서 제외해야 한다는 것입니다.
, 두하는 효과)에서는y의 .[x , y] 로, 두 번째 인수는
- 마우스 움직임을 등록하기 위해 x와 y의 변화를 관찰하는 것은 논리적으로 옳다.
- move Count를 감시 대상에서 제외하지 않으면 이 use Effect는 무한 사이클에 들어갑니다.변경을 감시하고 있는 것과 같은 값이 갱신되기 때문입니다.
이 기사는 나의 중간 출판물에서도 볼 수 있다.마음에 드시거나 의견이나 제안이 있으시면 미디엄에 박수를 치거나 댓글을 남겨주세요.
언급URL : https://stackoverflow.com/questions/53219164/what-s-the-difference-between-usestate-and-useeffect
'source' 카테고리의 다른 글
| MongoDB: 한 필드에 있는 모든 문서 업데이트 (0) | 2023.02.16 |
|---|---|
| 입력 유형 Number에서 +,-e를 차단하는 방법 (0) | 2023.02.16 |
| 최적의 사용자 역할 권한 데이터베이스 설계 프랙티스 (0) | 2023.02.16 |
| 중력 형태 오류 (0) | 2023.02.16 |
| jQuery - Ajax 경유로 JSON을 PUT하는 방법 (0) | 2023.02.16 |