programing

React.js에서 컴포넌트의 소품을 갱신할 수 있습니까?

bestcode 2022. 11. 17. 21:12
반응형

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

반응형