your programing

React 하위 구성 요소의 소품으로 상태를 업데이트하는 중

lovepro 2023. 4. 2. 12:15
반응형

React 하위 구성 요소의 소품으로 상태를 업데이트하는 중

리액트 앱은 부모 컴포넌트의 소품을 자녀 컴포넌트로 전달하고 소품을 자녀에게 상태를 설정합니다.

업데이트된 값을 상위 구성요소로 보낸 후 하위 구성요소가 업데이트된 소품으로 상태를 업데이트하지 않습니다.

자 컴포넌트의 상태를 갱신하려면 어떻게 해야 합니까?

내 축소 코드:

class Parent extends React.Component {
    constructor (props) {
        super(props);
        this.state = {name: ''} 
    }
    componentDidMount () {
        this.setState({name: this.props.data.name});
    }
    handleUpdate (updatedName) {
        this.setState({name: updatedName});
    }
    render () {
        return <Child name={this.state.name} onUpdate={this.handleUpdate.bind(this)} />
    }
}


class Child extends React.Component {
    constructor (props) {
        super(props);
        this.state = {name: ''} 
    }
    componentDidMount () {
        this.setState({name: this.props.name});
    }
    handleChange (e) {
        this.setState({[e.target.name]: e.target.value});
    }
    handleUpdate () {
        // ajax call that updates database with updated name and then on success calls onUpdate(updatedName)
    }
    render () {
        console.log(this.props.name); // after update, this logs the updated name
        console.log(this.state.name); // after update, this logs the initial name until I refresh the brower
        return <div>    
                    {this.state.name}
                    <input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
                    <input type="button" value="Update Name" onClick={this.handleUpdate.bind(this)} />
                </div>
    }
}

자녀에게 다음 사항을 구현해야 합니다.

componentWillReceiveProps(newProps) {
    this.setState({name: newProps.name});
}

편집: componentWillReceiveProps는 폐지되어 삭제됩니다만, 위의 docs 링크에 대체 제안이 있습니다.

부르기setState()componentWillReceiveProps는 추가 재렌더를 발생시키지 않습니다.소품을 받는 것은 하나의 렌더링과 이것입니다.setState는 componentDidUpdate와 같은 메서드 내에서 실행되는 경우 다른 렌더입니다.추천할 만한 것은this.state.name !== nextProps.name업데이트 여부를 항상 확인할 수 있도록 합니다.

componentWillReceiveProps(nextProps) {
    this.setState({name: nextProps.name});
}

shouldComponentUpdate(nextProps) {
    return this.state.name !== nextProps.name;
}

또한 상태를 갱신할 필요가 있는지 확인하는 것이 좋습니다.그것은 재렌더의 원인이 되기 때문입니다.

componentWillReceiveProps(newProps) {
  if (this.state.name !== newProps.name) {
    this.setState({name: newProps.name});
  }
}

몇 가지.클릭 시 함수를 바인딩하는 방법은 극히 이례적입니다.컨스트럭터에서 실행하거나 화살표 함수를 사용하는 것이 좋습니다(이것에 의해 함수는 자동적으로 클래스에 바인드 됩니다).

export default class Parent extends Component {

    constructor (props) {
        super(props);
        this.state = {name: ''} 
    }

    handleUpdate = (updatedName) => {
        this.setState({name: updatedName})
    }

    render () {
        return <Child name={this.state.name} onUpdate={this} />
    }
}

export default class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "" };
  }

  componentDidMount() {
    this.setState({ name: this.props.name });
  }

  handleChange = (e) => {
    this.setState({ name: e.target.value });
  }

  handleUpdate() {
    // ajax call that updates database with updated name and then on success calls onUpdate(updatedName)
  }

  render() {
    console.log(this.props.name); // after update, this logs the updated name
    console.log(this.state.name); // after update, this logs the initial name until I refresh the brower
    return (
      <div>
        {this.state.name}
        <input
          type="text"
          name="name"
          value={this.state.name}
          onChange={this.handleChange}
        />
        <input
          type="button"
          value="Update Name"
          onClick={this.handleUpdate}
        />
      </div>
    );
  }
}

또한 소품을 부모로부터 관리/업데이트할 것인지 자녀로부터 갱신할 것인지를 결정하도록 제안합니다.부모가 처리 상태를 책임지는 경우 handleUpdate를 부모에게 전파해야 합니다.

//@Parent component
<Child handleUpdate={()=> this.handleUpdate} .../>
//@Child component
handleUpdate = () => {
   this.props.handleUpdate
}

자녀에서 부모로 또는 그 반대로 소품을 관리하기 위해 다른 기능(React 16+)을 사용할 필요가 없습니다.

일반적으로 이러한 "양방향" 사례는 구조적인 "냄새"로, 각 구성요소의 우려 분리가 잘못 조정되었거나 아직 완전히 파악되지 않았음을 나타냅니다.

언급URL : https://stackoverflow.com/questions/39154967/updating-state-with-props-on-react-child-component

반응형