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

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

问题描述

为什么我们同时拥有道具?为什么我们不只有一个数据源?我想更新组件的 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的理念是道具应该是不可变的和自上而下的。这意味着父母可以将其喜欢的任何道具值发送给孩子,但孩子不能修改自己的道具。你做的是对传入的道具作出反应然后,如果你愿意,根据传入的道具修改你孩子的状态。

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.

所以你永远不要更新自己的道具道具,或父母的道具。永远。你只会更新你自己的状态,并对你父母给出的道具值作出反应。

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.

如果你想让一个孩子的动作发生在state,那么你所做的就是将一个回调传递给它可以根据给定的动作执行的子进程。然后,此回调可以修改父级的状态,然后可以在重新渲染时向子级发送不同的道具。

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中更新道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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