繁体   English   中英

数组中的React Child组件不会在prop更改时更新

[英]React Child components in an Array not updating on prop change

我想使用从父组件状态传递过来的prop更新数组中的所有子组件。 基本示例如下所示。 数组中的每个子组件都是无状态的,并且具有由父组件的状态确定的prop值。 但是,当父组件状态更改时,子组件不会随更改重新呈现。 当父母的状态发生变化时,我该如何重新渲染子组件? 谢谢!

import React from 'react';
import ReactDOM from 'react-dom';

class Child extends React.Component {

  render(){
    return (
      <p>
        <button onClick = {(e) => this.props.onClick(e)}>
        click me
        </button>
        {this.props.test}
      </p>
    )
};
}

class Parent extends React.Component{

  constructor(props){
    super(props);
    this.state = {msg: 'hello', child_array: []};
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e){
    e.preventDefault();
    const msg = this.state.msg == 'hello' ? 'bye' : 'hello';
    this.setState({msg: msg});
  }

  componentDidMount(){
    let store = [];

    for (var i = 0; i < 5; i++){
      store.push(<Child test = {this.state.msg} key = {i} onClick = {this.handleClick}/>);
    }
    this.setState({child_array: store});
  }

  render(){
    return(
      <div>
        {this.state.child_array}
      </div>
    )
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'));

问题在于您正在父级的componentDidMount()方法中渲染子级组件(并由此this.state.msg的值进行this.state.msg )。 您需要改为使用父级的render()方法来渲染它们。

如评论中所述

它不会再次重新渲染,因为您正在componentDidMount中生成Chil组件,并且第一次渲染后,每个组件仅对该方法调用一次。 因此,当您的回调触发时,child_array将为空

相反,您可以执行的操作是删除componentDidMount方法代码,然后在render中进行操作,如下所示。 在以下情况下,每次onclick在子组件中触发时,它将呈现

render(){
     const store = [];
     for (var i = 0; i < 5; i++){
        store.push(<Child test = {this.state.msg} key = {i} onClick = {this.handleClick}/>);
       }
       return(
            <div>
              {store}
            </div>
       )

componentWillReceiveProps将在您的情况下工作,每次您获得道具时,子组件都会重新渲染。

 class Child extends React.Component {
 constructor(props) {
  super(props);
  let initialData = (
  <p>
    <button onClick = {(e) => self.props.onClick(e)}>
    click me
    </button>
    {nextProps.test}
  </p>
 );
  this.state = {data: initialData };
 }
componentWillReceiveProps(nextProps) {
 let self = this;
 let updatedHtml = (
  <p>
    <button onClick = {(e) => self.props.onClick(e)}>
    click me
    </button>
    {nextProps.test}
  </p>
 );
 this.setState({data: updatedHtml})
}
render(){
 return (
  {data}
 )
 };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM