【问题标题】:Why props in React are read only?为什么 React 中的 props 是只读的?
【发布时间】:2018-12-28 08:22:15
【问题描述】:

React 文档说: React is pretty flexible but it has a single strict rule: all React components must act like pure functions with respect to their props.

为什么会这样?

我猜如果你直接改变props的值,组件不会重新渲染,这就是为什么我们必须使用setState。但我仍然不明白这背后的原因。为什么组件就其 props 而言必须像纯函数?

【问题讨论】:

标签: reactjs pure-function


【解决方案1】:

docs

React 文档说

所有 React 组件就其 props 而言必须像纯函数一样工作。 当然,应用程序 UI 是动态的,并且会随着时间而变化。在下一节中,我们将介绍一个新的“状态”概念。 State 允许 React 组件随着时间的推移更改其输出以响应用户操作、网络响应和其他任何内容,而不会违反此规则。

【讨论】:

    【解决方案2】:

    React 组件的重要概念:组件应该只管理自己的状态,而不应该管理自己的 props。

    其实一个组件的props具体来说就是“另一个组件(父组件)的状态”。所以道具必须由其组件所有者管理。 这就是为什么所有 React 组件在其 props 方面都必须像纯函数一样工作(而不是直接改变它们的 props)。

    我给你看一个简单的例子:

    class ParentComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          p1: {a:1, b:2},
        }
    
       render() {
          return <ChildComponent p1={this.state.p1} />     
       }
    }
    

    在 ChildComponent 中,如果你想改变“传递的 prop p1”(p1 是一个有自己的 ref 的对象)(例如在 ChildComponent 中,你写:p1.a=3),那么显然,“p1 - ParentComponent 状态的属性”也发生了变异。但是在这种情况下,ParentComponent 无法重新渲染,因为您没有在 ParentComponent 中触发动作setState()。 所以它会为一个不稳定的 React 应用程序产生许多不受控制的错误。

    我希望现在你能理解为什么 React 会这样说:

    严格的规则:所有 React 组件在其 props 方面都必须像纯函数一样工作(不能直接改变它们的 props)。


    奖励:为了正确更改(变异)道具,您必须在 ChildComponent 中使用“回调 fnc 道具”。目前,它很好地尊重了 React 组件的概念。

    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} />     
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多