programing

React : 소품 변경시 자식 구성 요소가 업데이트되지 않는 이유

nasanasas 2020. 10. 10. 10:08
반응형

React : 소품 변경시 자식 구성 요소가 업데이트되지 않는 이유


다음 의사 코드 예제에서 컨테이너가 foo.bar를 변경할 때 Child가 다시 렌더링하지 않는 이유는 무엇입니까?

Container {
  handleEvent() {
    this.props.foo.bar = 123
  },

  render() {
    return <Child bar={this.props.foo.bar} />
}

Child {
  render() {
    return <div>{this.props.bar}</div>
  }
}

forceUpdate()Container에서 값을 수정 한 후 호출하더라도 Child는 여전히 이전 값을 보여줍니다.


부모의 소품이 변경되면 자식은 다시 렌더링되지 않지만 STATE가 변경되면 :)

당신이 보여주는 것은 이것입니다 : https://facebook.github.io/react/tips/communicate-between-components.html

소품을 통해 부모에서 자식으로 데이터를 전달하지만 rerender 로직이 없습니다.

일부 상태를 부모로 설정 한 다음 부모 변경 상태에서 자식을 다시 렌더링해야합니다. 이것이 도움이 될 수 있습니다. https://facebook.github.io/react/tips/expose-component-functions.html


이름과 동일한 '키'속성을 갖도록 하위를 업데이트하십시오. 키가 변경 될 때마다 구성 요소가 다시 렌더링됩니다.

Child {
  render() {
    return <div key={this.props.bar}>{this.props.bar}</div>
  }
}

나는 같은 문제가 있었다. 이것이 내 해결책입니다. 이것이 좋은 방법인지 잘 모르겠습니다. 그렇지 않은 경우 알려주세요.

state = {
  value: this.props.value
};

componentDidUpdate(prevProps) {
  if(prevProps.value !== this.props.value) {
    this.setState({value: this.props.value});
  }
}

UPD : 이제 React Hooks를 사용하여 동일한 작업을 수행 할 수 있습니다. (구성 요소가 함수 인 경우에만)

const [value, setValue] = useState(propName);
// This will launch only if propName value has chaged.
useEffect(() => { setValue(propName) }, [propName]);

React 철학 구성 요소에 따르면 소품을 변경할 수 없습니다. 부모로부터 받아야하며 불변이어야합니다. 부모 만 자식의 소품을 변경할 수 있습니다.

상태 대 소품 에 대한 좋은 설명

또한이 스레드를 읽으십시오 . react.js에서 props를 업데이트 할 수없는 이유는 무엇입니까?


setState기능 을 사용해야 합니다. 그렇지 않은 경우 forceUpdate를 사용하는 방법에 관계없이 state는 변경 사항을 저장하지 않습니다.

Container {
    handleEvent= () => { // use arrow function
        //this.props.foo.bar = 123
        //You should use setState to set value like this:
        this.setState({foo: {bar: 123}});
    };

    render() {
        return <Child bar={this.state.foo.bar} />
    }
    Child {
        render() {
            return <div>{this.props.bar}</div>
        }
    }
}

코드가 유효하지 않은 것 같습니다. 이 코드를 테스트 할 수 없습니다.


setState 함수를 사용하십시오. 그래서 당신은 할 수 있습니다

       this.setState({this.state.foo.bar:123}) 

inside the handle event method.

Once, the state is updated, it will trigger changes, and re-render will take place.


You should probably make the Child as functional component if it does not maintain any state and simply renders the props and then call it from the parent. Alternative to this is that you can use hooks with the functional component (useState) which will cause stateless component to re-render.

Also you should not alter the propas as they are immutable. Maintain state of the component.

Child = ({bar}) => (bar);

참고URL : https://stackoverflow.com/questions/38892672/react-why-child-component-doesnt-update-when-prop-changes

반응형