javascript - React 动态渲染组件(对象分配与函数返回)

标签 javascript reactjs

我在这里碰壁了,这意味着我无法完全弄清楚为什么接下来的两个版本的代码表现如此不同。

在第一个版本中,当我初始化 this.childComponent = (<ChildComp />) 时,当我更改 Parent 时,它的 props 似乎没有更新的状态(通过 setState() )。即使 setState() 也会发生这种情况实际上被调用,并且 Parent的状态已更新。

在第二个版本中,当我实际初始化一个返回组件( this.childComponent = () => {return (<ChildComp />)} )的函数时,一切都像魅力一样工作, Prop 会更新。 我正在使用第二个版本(因为它有效),但我想了解为什么它有效而第一个版本无效。

这是子组件:

class Child extends React.Component {
  render() {
    return (
      <button onClick=(this.props.setValue())>
        {this.props.value}
      </button>
    )
  }
}

我有父组件的接下来两个版本:

1.

class Parent extends React.Component {
  constructor() {
    this.state = {
      value: 1
    }
    this.childComponent = (
      <Child value={this.state.value} 
      setValue={() => this.setValue()}/>
    )
  }
  setValue() {
    this.setState({value: 2})
  }
  render () {
    return ( {this.childComponent} )
  }  
}

2.(this.childComponent 现在是一个返回 React 元素的函数)

class Parent extends React.Component {
  constructor() {
    this.state = {
      value: 1
    }
    this.childComponent = () => {
      return (
        <Child value={this.state.value} 
        setValue={() => this.setValue()}/>
      )
    }
  }
  setValue() {
    this.setState({value: 2})
  }
  render () {
    return ( {this.childComponent()} )
  }   
}

我尝试简化代码,以便我的问题更容易理解。

提前谢谢

最佳答案

React 使用名为 reconciliation 的策略每次内部状态发生变化时都可以有效地更新 DOM。通常,这发生在 setState 之后打电话。

在第一个示例中,render Parent 内的方法组件始终返回相同的 Child组件,因为它在 constructor 中仅创建一次。因此,协调算法不会发现任何更改,因为没有任何更改。

我想指出<Child value={this.state.value} setValue={() => this.setValue()}/>只是 React.createElement(Child, {value: this.state.value, setValue: () => this.setValue()}, null) 的语法糖。 createElement只是返回一个对象。

在第二个示例中,每个 render打电话,你打电话childComponent这又创建了一个新的 Child组件。

关于javascript - React 动态渲染组件(对象分配与函数返回),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44281305/

相关文章:

javascript - ion-toggle ng-change 无法通过 Controller + 服务结构正确触发

javascript - 如何修复react-redux中循环依赖导致的 'Invariant Violation'

javascript - 如何在React中做vanilla js等效的appendChild?

javascript - React.js : Rendering Components from Array of Objects

javascript - 如何从父组件访问路由信息?

javascript - 带有 MySQL 句柄的 Node.js REST 重新连接

javascript - "fs.writefile"函数中的自定义文件名

javascript - html5 视频回退/备份图像不合适......?

javascript - 如何使用 token 在 Angular Material 表中设置服务器端分页

javascript - 将元素拖到其可滚动父 div 之外 - ( React-Draggable )