componentWillReceiveProps에서 변경된 소품을 확인하는 방법
(오래된 소품을 다른 곳에 보관하지 않고) 내부에 어떤 소품이 변경되었는지 확인할 수 있는 방법이 있습니까?componentWillReceiveProps?
예.
componentWillReceiveProps (newProps) {
if( /* newProps.profileImage is different to previous props */ ) /* do stuff */
}
이 함수는componentWillReceiveProps는 폐지되었습니다.공식 문서 인용:
사용하시는 경우
componentWillReceiveProps일부 데이터를 다시 복구하려면 대신 메모 도우미를 사용하십시오.
이것은 당신의 수표가 안에 있는 경우를 말합니다.componentWillReceiveProps불필요하게 같은 것을 여러 번 재계산하는 것을 피하기 위해서였다.링크된 블로그 게시물에서는 비싼 기능의 결과를 캐싱하여 재계산하는 것이 아니라 조회할 수 있도록 제안하고 있습니다.이것은 memoize-one 등의 도우미를 사용하여 수행할 수 있습니다.
사용하시는 경우
componentWillReceiveProps받침대가 변경될 때 일부 상태를 "조절"하려면, 대신 키로 구성요소를 완전히 제어하거나 완전히 제어하지 않도록 하는 것을 고려하십시오.
다시 한 번 링크된 블로그 투고에서는 이에 대해 더 자세히 설명하지만 간략하게 설명하겠습니다.
- "완전 제어" 컴포넌트는 상태가 없는 기능 컴포넌트를 참조합니다(상위 컴포넌트는 상태를 처리합니다).
- '완전 제어되지 않은' 대체 방법은
props초기 상태를 설정한 다음 소품 변경 사항을 모두 무시합니다.
매우 드문 경우지만
getDerivedStateFromProps라이프 사이클을 실현합니다.
이 함수는 다음을 수신합니다.(props, state)이전 상태로의 변경을 되돌립니다.render원하는 것을 할 수 있는 통제권을 주는 것입니다.
원래 답변(이전 버전의 React용)
이 라이프 사이클 방법이 호출되는 시점에서this.props앞서 말한 소품 세트를 말합니다.
단일 속성을 비교하려면foo새 소품들은 기존 소품들과 같은 성질을 가지고 있어서 비교해보면 된다.newProps.foo와 함께this.props.foo예시는 다음과 같습니다.
componentWillReceiveProps (newProps) {
if( newProps.profileImage !== this.props.profileImage ) /* do stuff */
}
또한 모든 소품을 루프하여 무엇이 변경되었는지 확인할 수 있습니다.
componentWillReceiveProps(nextProps) {
for (const index in nextProps) {
if (nextProps[index] !== this.props[index]) {
console.log(index, this.props[index], '-->', nextProps[index]);
}
}
}
React 16.3, componentWillReceiveProps는 사용하지 않는 것이 좋으므로 react 웹사이트에서 secure_componentwillreceiveprops 설명서를 참조하십시오.
사용하다getDerivedStateFromProps대신:
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.profileImage !== prevState.profileImage ) {
return {stateFoo: 'valueBar'};
}
}
반환되는 값은 다음과 같이 동작합니다.setState.
아직 비교할 수 있는 것은this.props.profileImage다음 시간까지 업데이트되지 않기 때문입니다.componentWilReceiveProps호출됩니다.예를 들어 docs에서는 다음 예를 사용합니다.
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
미래에 이걸 찾는 사람에게 보내는 메모로요componentWillReceiveProps()는 폐지될 예정입니다.이제 get Derived State From Props()를 사용할 것을 권장합니다.그 이유에 대해서는, https://reactjs.org/blog/2018/03/29/react-v-16-3.html#component-lifecycle-changes 를 참조해 주세요.
네, 특정 소품 변경 여부를 확인하실 수 있습니다. this.props바뀌기 전의 소품을 말합니다.예를 들어 다음과 같습니다.
componentWillReceiveProps(newProps) {
if( newProps.profileImage != this.props.profileImage ) {
/* do stuff */
}
}
주의: 메서드를 호출할 때마다 반드시 소품이 바뀌는 것은 아니기 때문에 어떤 소품이 변경되었는지 테스트해 볼 필요가 있습니다.
다음과 같은 로직을 구현해야 합니다.
import React from 'react';
import { View, Dimensions } from 'react-native';
class DataTable extends React.Component {
state = {
previousProps: null // Keep snapshot of current props in State & never change this through setState()
}
static getDerivedStateFromProps(props, currentState) {
if (JSON.stringify(props) === JSON.stringify(currentState.previousProps)){
//Here it's mean that props are not changed!!!
return null;
}
//Here it's mean props are changed!
//Here You find out what are changed through looping
//Don't forget to return new props as a state here!
return {
previousProps: props,
//...Pass your new state depending on new props here!
}
}
render() {
return(
<View>
{...}
</View>
)
}
}
언급URL : https://stackoverflow.com/questions/38654750/how-to-check-what-props-changed-in-componentwillreceiveprops
'programing' 카테고리의 다른 글
| Angular UI-Router의 한 상태에서 더 많은 옵션 파라미터 (0) | 2023.03.19 |
|---|---|
| Wordpress rest api에서 초안 가져오기 금지 (0) | 2023.03.19 |
| mysql CLI는 연결할 수 있지만 WordPress는 연결할 수 없는 이유는 무엇입니까? (0) | 2023.03.19 |
| html 대신 일반 텍스트를 출력하는 angularjs (0) | 2023.03.19 |
| DD/MM/YYY 날짜 형식(Moment.js) (0) | 2023.03.19 |