【问题标题】:React Child components in an Array not updating on prop changeReact 数组中的子组件不会在道具更改时更新
【发布时间】:2019-03-03 22:34:10
【问题描述】:

我想使用从父组件状态传递下来的道具来更新数组中的所有子组件。下面显示了一个基本示例。数组中的每个子组件都是无状态的,并且具有由父组件的状态确定的 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 中生成子组件,并且在第一次渲染后每个组件只调用一次此方法。因此,当您的回调触发时,child_array 将为空

标签: javascript reactjs


【解决方案1】:

如cmets中所述

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

相反,您可以做的是删除 componentDidMount 方法代码并在渲染中执行该操作,如下所示。在以下情况下,每次在子组件中触发 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>
       )

【讨论】:

    【解决方案2】:

    问题在于您在父级的componentDidMount() 方法中渲染子组件(并因此烘焙this.state.msg 的值)。您需要改为在父级的 render() 方法中呈现它们。

    【讨论】:

      【解决方案3】:

      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}
       )
       };
      }
      

      【讨论】:

      • 此方法已弃用,不应在新代码中使用。
      猜你喜欢
      • 2018-08-09
      • 2020-01-19
      • 2021-06-15
      • 2016-12-17
      • 2021-09-01
      • 2020-06-17
      • 2019-05-25
      • 1970-01-01
      相关资源
      最近更新 更多