기능 컴포넌트가 있는 컨스트럭터를 지정하는 방법(팻 화살표 구문)
다음 컴포넌트가 지정됩니다.
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
const NewGoalInput = props => {
return (
<input type="text" onKeyUp={handleKeyUp}/>
)
}
const handleKeyUp = (e) => {
if (e.key === "Enter") {
// TODO Add goal
}
}
export default NewGoalInput
constructor를 사용하지 않고 상태를 정의할 수 있는 생성자를 추가하려면 어떻게 해야 합니까?extends React.Component
구문?
스테이트리스 컴포넌트이기 때문에 컴포넌트의 라이프 사이클은 없습니다.그 때문에, 다음의 항목을 지정할 수 없습니다.constructor
.
연장해야 합니다.React.Component
스테이트풀 컴포넌트를 작성하기 위해서는 컨스트럭터가 필요하며 사용자는 이 컴포넌트를 사용할 수 있습니다.state
.
업데이트 React 16.8.0 및 Hooks가 도입된 이후 더 많은 옵션이 있습니다.
후크는 클래스를 작성하지 않고 상태 및 기타 React > 기능을 사용할 수 있는 새로운 기능 제안입니다.> v16.8.0의 일부로 React에서 출시됩니다.
스테이트리스:
import React from "react"
const Stateless = ({name}) => (
<div>{`Hi ${name}`}</div>
);
스테이트풀:
컴포넌트의 라이프 사이클 방법 및 로컬 상태에 액세스 할 수 있습니다.
class Stateful extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
componentDidUpdate() {
const { count } = this.state;
document.title = `You've clicked ${count} times.`;
}
render() {
const { count } = this.state;
return (
<div>
<p>You've clicked {count} times.</p>
<button onClick={() => this.setState({ count: count + 1 })}>
Click me
</button>
</div>
);
}
}
후크 사용:
사용할 수 있다State Hook
그리고.Effect Hook
.
React 클래스의 라이프 사이클 메서드에 익숙한 경우 useEffect Hook을 componentDidMount, componentDidUpdate 및 componentWillUnmount가 결합된 것으로 생각할 수 있습니다.
import React, { useState, useEffect } from "react";
const UsingHooks = () => {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You've clicked ${count} times.`;
});
return (
// <> is a short syntax for <React.Fragment> and can be used instead of a wrapping div
<>
<p>You've clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</>
);
}
이왕이면useState
훅이 좀 구식인 것 같아요.제가 잘못하고 있었기 때문에 이 질문을 하게 되었습니다.여기 제가 하고 있던 간단한 코드가 있습니다.
// set an initial state
const [ value, setValue ] = useState(0)
// gets called after component is re-rendered
useEffect(() => {
// callback to parent that set props
props.update()
})
// if we have an existing value passed in
if (props.value) {
setValue(props.value)
}
이 코드는 훅을 사용하여 스테이트풀 클래스에서 함수로 변환되었습니다.원래는 컨스트럭터에 기본 소품을 설정했지만 함수에 컨스트럭터가 없고 컴포넌트가 재렌더될 때마다 체크가 이루어집니다.
- 콜
useState
- 트리거 재실행
- useEffect가 트리거됩니다.
- 부모는 소품을 세팅하는 것으로 불린다.
- 아이가 다시 렌더링할 수 있도록 소품
- GOTO 1
보시다시피 무한 루프 상태가 됩니다.해결책은 매우 간단합니다.여기 원본과 다른 모조품이 있습니다.
- const [ value, setValue ] = useState(0)
+ const [ value, setValue ] = useState(props.value || 0)
- if (props.value) {
- setValue(props.value)
- }
기본적으로, 소품에서 상태를 초기화하고 전화하는 것과 같은 어리석은 행동은 하지 마세요.useState
이벤트 또는 특정 유형의 콜백에 대한 응답은 제외합니다.
사용할 수 있습니다.useMemo
훅(아래와 같이)을 사용하여 기능 구성 요소의 생성자로 시연합니다.누군가가 사용하자고 제안했습니다.useEffect
렌더링 후에 호출됩니다.
useMemo(() => {
console.log('This is useMemo')
}, []);
기능 컴포넌트의 첫 번째 행으로 useState를 설정하고 함수를 "초기값"으로 추가할 수 있습니다.
const MyComponentName = props => {
useState(() => {
console.log('this will run the first time the component renders!');
});
return <div>my component!</div>;
};
넌 아냐.이 예의 컴포넌트의 종류를 "스테이트리스 기능 컴포넌트"라고 부릅니다.상태 및 라이프 사이클 메서드가 없습니다.컴포넌트를 스테이트풀하게 하려면 클래스 컴포넌트로 작성해야 합니다.
FC에서 컨스트럭터를 시뮬레이션하려면 useEffect를 사용합니다.
useEffect(() => {
... here your init code
}, []);
바로 그거야!EZ! 이 useEffect는 컴포넌트가 로드될 때 한 번만 실행되며 이후 실행되지 않습니다.단, 마지막에 대괄호를 추가하는 것을 잊지 마십시오.
컴포넌트를 마운트하기 전에 함수를 한 번 실행하고 싶은 사용자를 위해 후크(TypeScript로 작성)가 있습니다.
통상은 「」입니다.useEffect
★★★★★★★★★★★★★★★★★」useLayoutEffect
컴포넌트가 마운트된 후에 실행되며, 그 전에 코드를 실행하고 싶은 경우도 있습니다(컨스트럭터 등).
import React, { useRef } from "react";
function useOnce<Type>(callBack: () => Type): Type {
const result = useRef<Type | null>(null);
if (result.current !== null) {
return result.current;
}
result.current = callBack();
return result.current;
}
const Component: React.FC<{}> = () => {
const result = useOnce(() => {/* Code you would normally put in a constructor */});
return <div />
}
또는 react-afc를 사용할 수 있습니다.
import { afc, reactive } from 'react-afc'
function heavyCalc() {/*...*/}
const Conponent = afc(props => {
// Called once, before the first render
const state = reactive({
name: 'Stack',
inputsCount: 0
})
// Without useMemo(..., [])
const result = heavyCalc()
// The function is created once and does not cause
// a re-render of child components
function onInput(e) {
state.inputsCount++
state.name = e.currentTarget.value
}
// Saved between renders (no longer need useRef)
let rendersCount = 0
// Must return the render-function
return () => {
// The function works like a regular react-component
// Here you can use the usual hooks
rendersCount++
return (
<input onChange={onInput} value={state.name}/>
)
}
})
패키지에는 상태(rex 포함), 리액트 훅, 라이프 사이클 방법 및 컨텍스트에 필요한 방법이 있습니다.
언급URL : https://stackoverflow.com/questions/44263915/how-to-specify-a-constructor-with-a-functional-component-fat-arrow-syntax
'sourcetip' 카테고리의 다른 글
JSF(Primefaces) ID별 여러 요소의 Ajax 업데이트 (0) | 2023.03.14 |
---|---|
@Autowired Bean은 Spring Boot Unit 테스트에서 NULL입니다. (0) | 2023.03.14 |
MySQL 데이터베이스에서 WordPress 버전 확인 (0) | 2023.03.14 |
커스텀 퍼머링크 구조: /% custom-post-type%/% custom-taxonomy%/%post-name%/ (0) | 2023.03.14 |
하드코드된 JSON 문자열을 변수에 저장 (0) | 2023.03.14 |