为什么React中的道具是只读的?

时间:2018-07-20 05:12:31

标签: reactjs pure-function

React文档说: openssl enc

那是为什么?

我猜想,如果直接更改道具的值,该组件不会重新渲染,这就是为什么我们必须使用df = df.withColumn('random_index',rand()) df = df.orderBy('random_index') df.write.csv('hdfs:///user/yananc/yanan_gbdt_dnn', sep=',') 的原因。但我仍然不了解其背后的原因。为什么组件在其道具方面必须像纯函数一样?

2 个答案:

答案 0 :(得分:4)

React组件的重要概念:组件只能管理自己的状态,而不能管理自己的道具。

实际上,组件的 props具体是“另一个组件(父组件)的状态” 。因此道具必须由其组件所有者管理。这就是为什么所有React组件在其prop上都必须像纯函数一样起作用(而不是直接对其prop进行突变)。

我将向您展示一个简单的示例:

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      p1: {a:1, b:2},
    }

   render() {
      return <ChildComponent p1={this.state.p1} />     
   }
}

在ChildComponent中,如果您想对“通过的道具p1”进行突变(p1是具有自己引用的对象)(例如,在ChildComponent中,您编写:p1.a=3),显然,“ p1-ParentComponent状态的属性”也发生了变化。但是在这种情况下,ParentComponent无法重新渲染,因为您没有在ParentComponent中触发动作setState()因此,它将为React App不稳定生成许多不受控制的错误。

我现在希望您能理解React为什么说:

严格的规则:所有React组件在其prop上都必须像纯函数一样起作用(而不是直接对其prop进行突变)。


奖金:要正确更改(变异)道具,必须在ChildComponent中使用“回调fnc道具”。现在,它很好地尊重了React Component的概念。

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      p1: {a:1, b:2},
  }

  this.changeP1 = () => {
     this.setState({p1: {a:3, b:4}});
  }

   render() {
      return <ChildComponent p1={this.state.p1} changeP1={this.changeP1} />     
   }
}

答案 1 :(得分:0)

docs

反应文档说

所有React组件在其道具方面都必须像纯函数一样发挥作用。 当然,应用程序UI是动态的,并且会随着时间而变化。在下一节中,我们将介绍“状态”的新概念。状态允许React组件随时间更改其输出,以响应用户操作,网​​络响应和其他任何情况,而不会违反此规则。