【问题标题】:Child components not updating while in array React Native子组件在数组 React Native 中未更新
【发布时间】:2021-08-31 10:53:36
【问题描述】:

我正在尝试更新具有父状态道具的子组件。在将 setState() 更改为我的知识的父级状态时,chlid 应该重新渲染。但是当孩子在数组中时,不会发生重新渲染。我该如何解决? 提前致谢。

我的孩子班:

class Child extends Component {
  render() {
    return(
      <Text>{this.props.state.isActive.toString()}</Text>
    )
  }
}

我的父类:

class Parent extends Component {

  state = {
    isActive: false
  }

  children = []


  constructor(props) {
    super(props)
    this.createChildren()
    this.changeState()
  }

  changeState() {
    this.change = setInterval(() => {
      if(this.state.isActive){
        this.setState({isActive: false})
      } else {
        this.setState({isActive: true})
      }
    }, 1000)
  }


  componentWillUnmount() {
    clearInterval(this.change)
  }

  createChildren() {
    for(let i=0; i<5; i++) {
      this.children.push(<Child key={i} state={this.state}/>)
    }
  }

  render() {
    return(
      <View>
        {this.children}
      </View>
    )
  }
}

我的应用功能:

export default function App() {
  return (
    <View style={style.conteiner}>
      <Parent/>
    </View>
  );
} 

【问题讨论】:

标签: reactjs react-native


【解决方案1】:

应始终在渲染期间创建 React 元素。不要将它们存储在属性或组件状态中:

  renderChildren = () => {
    children = [];

    for(let i=0; i<5; i++) {
      children.push(<Child key={i} state={this.state}/>)
    }

    return children;
  }

  render() {
    return(
      <View>
        {this.renderChildren()}
      </View>
    )
  }

您基本上总是渲染您在构造函数中创建的元素(这也是一种反模式)。

【讨论】:

    【解决方案2】:

    您正在做的事情不会起作用,因为您将&lt;Child/&gt; 组件推送到仅在constructor 内部调用的类属性;所以这些&lt;Child/&gt; 组件将只引用初始状态,而不是现在更新的状态。您必须在渲染中调用 getChildren() 函数。我已经在 react 中解决了这个问题,你可以翻译成 react native 用 Views 替换 divs,参见代码框:https://codesandbox.io/s/pedantic-jackson-wgtnh?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2021-05-08
      • 2021-12-27
      • 2017-05-10
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      相关资源
      最近更新 更多