[英]Is there a way to update react component without using props?
I want to update a react component from another component not connected to each other via props.我想从另一个未通过 props 相互连接的组件更新一个反应组件。 How can i?
我怎么能够?
You'd have to use state somewhere above the level of both of the components.您必须在两个组件级别以上的某个位置使用 state 。 Then you have to have a method to change that state which then passes the data down via props.
然后你必须有一种方法来改变 state 然后通过道具传递数据。
Edit: So, you need to have some sort of state management, either by hooks context or some other state management, like redux, mobx, etc. For quick and dirty, use useContext.编辑:所以,你需要有某种 state 管理,通过钩子上下文或其他一些 state 管理,如 redux,使用上下文等。
If you use classes you can do:如果你使用类,你可以这样做:
this.forceUpdate();
You can pass key as props and give it an updated value in that.您可以将key作为 props 传递并为其提供更新的值。
but, theres a catch.但是,有一个陷阱。 When key updates, react will recreate that component in the component tree, ie, it will unmount and remount
当 key 更新时,react 将在组件树中重新创建该组件,即它将卸载并重新安装
<Component key={some-value-that-updates}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.