从另一个组件更新组件状态的最简单方法是什么?可以说组件是兄弟姐妹吗? [英] What is the most simplest method of updating component's state from another component? Lets say components are siblings?

查看:70
本文介绍了从另一个组件更新组件状态的最简单方法是什么?可以说组件是兄弟姐妹吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Web应用程序中创建一个交互式功能.在一个组件中选择一个选项后,我想更新另一个组件的状态并触发重新渲染.我应该怎么做.

I am trying to create an interactive feature in my web application. Upon selecting an option in one component I want to update state of another component and trigger re-render. How should I go about this.

推荐答案

您可以将两个组件都放在另一个组件中,然后在那定义状态和setState.现在,将setState作为prop发送到第一个组件.选择选项时,请使用已发送的setState设置状态.现在,如果第二个组件使用该状态作为道具,那么它将被重新渲染.

You can put both the components inside another component and define the state and setState over there. Now send the setState as a prop to the first component. when you select an option set the state using the setState you have sent. Now, if the second component is using that state as prop, then it will be rerendered.

ParentComponent

ParentComponent

  • 定义状态

  • define the state

FirstComponent将setState作为Prop

FirstComponent takes setState as Prop

SecondComponent的状态为Prop

SecondComponent takes the state as Prop

So, in your case, if the second component's state is defined in the parent, we can send its setState as prop to the first component and when a value is selected, change the state in the first component itself.它将更改存在于父级中的状态,该状态将重新呈现第二个组件,因为该状态是第二个组件中的道具.

So, in your case, if the second component's state is defined in the parent, we can send its setState as prop to the first component and when a value is selected, change the state in the first component itself. It will change the state present in the parent which will rerender the second component since that state is a prop in second component.

这篇关于从另一个组件更新组件状态的最简单方法是什么?可以说组件是兄弟姐妹吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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