为什么我不能在 react.js 中更新 props? [英] Why can't I update props in react.js?

查看:30
本文介绍了为什么我不能在 react.js 中更新 props?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们同时拥有 stateprops?为什么我们不只有一个数据源?我想更新组件的 props 并让它重新渲染自身及其所有子组件.看起来很简单,但我不知道如何让组件更新它自己或其父级的 props.

Why do we have both state and props? Why don't we just have one source of data? I'd like to update a component's props and have it re-render itself and all of its children. Seems simple but I can't figure out how to let a component update its own or its parent's props.

感谢您的帮助.

推荐答案

React 哲学是 props 应该是不可变的和自上而下的.这意味着父母可以将它喜欢的任何道具值发送给孩子,但孩子不能修改自己的道具.您所做的是对传入的道具做出反应,然后,如果您愿意,可以根据传入的道具修改孩子的状态.

The React philosophy is that props should be immutable and top-down. This means that a parent can send whatever prop values it likes to a child, but the child cannot modify its own props. What you do is react to the incoming props and then, if you want to, modify your child's state based on incoming props.

因此,您永远不会更新自己的道具或父母的道具.曾经.你只更新你自己的状态,并对父级给你的 prop 值做出反应.

So you don't ever update your own props, or a parent's props. Ever. You only ever update your own state, and react to prop values you are given by parent.

如果您希望在子节点上发生一个操作来修改状态上的某些内容,那么您要做的就是将回调传递给子节点,它可以在给定的操作上执行该回调.然后,此回调可以修改父级的状态,然后可以在重新渲染时将不同的道具发送给子级.

If you want to have an action occur on a child which modifies something on the state, then what you do is pass a callback to the child which it can execute upon the given action. This callback can then modify the parent's state, which in turns can then send different props to the child on re-render.

这篇关于为什么我不能在 react.js 中更新 props?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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