gpt4 book ai didi

reactjs - 为什么 React 中的 props 是只读的?

转载 作者:行者123 更新时间:2023-12-03 13:24:51 24 4
gpt4 key购买 nike

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 必须像纯函数一样?

最佳答案

The important concept of React component: a component should only manage its own state, but it should not manage its own props.

In fact, props of a component is concretely "the state of the another component (parent component)". So props must be managed by their component owner. That's why all React components must act like pure functions with respect to their props (not to mutate directly their 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 是一个具有自己引用的对象)(例如,在 ChildComponent 中,您可以编写:p1.a=3 ),显然,“p1 - ParentComponent 状态的属性”也发生了变化。但在这种情况下,ParentComponent 无法重新渲染,因为您没有触发 ParentComponent 中的操作 setState()因此,对于不稳定的 React App 来说,它会产生许多不受控制的错误。

I hope right now that you can understand why React says:

The strict rule: all React components must act like pure functions with respect to their props (not to mutate directly their props).

<小时/>

奖励:为了正确更改(改变) Prop ,您必须在 ChildComponent 中使用“callback fnc prop”。现在,它很好地尊重了 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} />
}
}

关于reactjs - 为什么 React 中的 props 是只读的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com