React.js에서 컴포넌트의 소품을 갱신할 수 있습니까?
React.js와 함께 작업을 시작하고 나서props
(부모 컴포넌트에서 전달되는) 정적인 반면,state
이벤트를 기반으로 한 변경.다만, 이 문서에는, 특히 다음의 예가 기재되어 있는 에 대한 참조가 기재되어 있습니다.
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
이는 컴포넌트의 속성이 다음과 같은 비교를 바탕으로 변경될 수 있음을 암시하는 것으로 보입니다.nextProps
로.this.props
.제가 무엇을 빠뜨리고 있나요?소품들은 어떻게 변하나요? 아니면 제가 이걸 어디라고 부르는지 잘못 알고 있나요?
컴포넌트는 어레이나 오브젝트가 아니면 자신의 소품을 갱신할 수 없지만(가능한 한 컴포넌트가 안티패턴이라도 자신의 소품을 갱신할 수 있다) 상태는 갱신할 수 있습니다.
예를 들어 대시보드에는speed
이 속도를 표시하는 게이지 자식으로 전달합니다.그것의.render
방법은 정당하다return <Gauge speed={this.state.speed} />
. 대시보드가 호출할 때this.setState({speed: this.state.speed + 1})
의 새로운 값으로 게이지가 재렌더됩니다.speed
.
이런 일이 일어나기 전에 게이지의componentWillReceiveProps
이 호출되므로 게이지가 새 값을 이전 값과 비교할 수 있습니다.
소품
React 구성 요소는 변경할 수 있지만 다른 구성 요소에서만 변경할 수 있는 정보를 저장하기 위해 소품을 사용해야 합니다.
주
React 구성 요소는 상태를 사용하여 구성 요소 자체를 변경할 수 있는 정보를 저장해야 합니다.
좋은 예가 발레리에 의해 이미 제공되고 있다.
구성요소의 상위 구성요소가 다른 특성을 사용하여 구성요소를 다시 렌더링하면 소품이 변경될 수 있습니다.대부분의 경우 새로운 컴포넌트를 인스턴스화할 필요가 없는 최적화라고 생각합니다.
예를 들어, 후크와 함께 많은 것이 변경되었습니다.componentWillReceiveProps
로 변했다useEffect
+useRef
(다른 SO 답변과 같이) 단, Propes는 읽기 전용이므로 호출자 메서드만 업데이트해야 합니다.
소품 배열인 경우 업데이트 트릭:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: this.props.count
}
}
increment(){
console.log("this.props.count");
console.log(this.props.count);
let count = this.state.count
count.push("new element");
this.setState({ count: count})
}
render() {
return (
<View style={styles.container}>
<Text>{ this.state.count.length }</Text>
<Button
onPress={this.increment.bind(this)}
title={ "Increase" }
/>
</View>
);
}
}
Counter.defaultProps = {
count: []
}
export default Counter
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
사용하시는 경우recompose
,사용하다mapProps
들어오는 소품에서 새로운 소품을 만들다
예:
import { compose, mapProps } from 'recompose';
const SomeComponent = ({ url, onComplete }) => (
{url ? (
<View />
) : null}
)
export default compose(
mapProps(({ url, storeUrl, history, ...props }) => ({
...props,
onClose: () => {
history.goBack();
},
url: url || storeUrl,
})),
)(SomeComponent);
언급URL : https://stackoverflow.com/questions/24939623/can-i-update-a-components-props-in-react-js
'programing' 카테고리의 다른 글
SQLSTATE [ 42000 ]:구문 오류 또는 액세스 위반: SELECT 목록의 1055 식 #3이 GROUP BY 절에 없고 집계되지 않은 것을 포함합니다. (0) | 2022.11.17 |
---|---|
python에서 반복적으로 폴더 삭제 (0) | 2022.11.17 |
JHipster 6.0.1: 리퀴베이스 태스크 실패 (0) | 2022.11.17 |
여러 테이블에서 선택 - 1 대 다 관계 (0) | 2022.11.17 |
Python 운영체제는 어떻게 확인하나요? (0) | 2022.11.17 |