为什么 React props 是不可变的? [英] Why are React props immutable?

查看:64
本文介绍了为什么 React props 是不可变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 React 的快速入门 文档;

I've been reading React's Quick Start documentation;

无论将组件声明为函数还是类,它都不能修改自己的 props

Whether you declare a component as a function or a class, it must never modify its own props

这是一个纯"函数,因为它不会尝试改变它的输入,并且对于相同的输入总是返回相同的结果:

This is a "pure" function, because it doesn't attempt to change its inputs, and always returns the same result for the same inputs:

function sum(a, b) {
  return a + b;
}

这是一个不纯"的函数,因为它改变了自己的输入:https://codesandbox.io/s/9z38xv4x7r

This in an "impure" function, because it changes its own input: https://codesandbox.io/s/9z38xv4x7r

function SayHi(props) {
  props.name = "Jim"; // TypeError Cannot assign to read only property 'name' of object '#<Object>'
  return <h1>Hi {props.name}!</h1>;
}

为什么 React props 是只读的?

Why are React props read-only?

推荐答案

组件应该管理自己的状态,但不应该管理自己的道具.props 本质上是由组件所有者管理的状态".这就是为什么 props 不可变.

A component should manage its own state, but it should not manage its own props. props is essentially "state that is managed by the component owner." That's why props are immutable.

React 文档还建议将状态视为不可变的.那是因为通过直接操作 this.state 会绕过 React 的状态管理,这可能是危险的,因为之后调用 setState() 可能会替换 mutation 你做的.

React docs also recommends to treat state as if it's immutable. That is because by manipulating this.state directly you are circumventing React’s state management, which can be potentially dangerous as calling setState() afterwards may replace the mutation you made.

这篇关于为什么 React props 是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆