简体   繁体   English

有没有办法在不使用道具的情况下更新反应组件?

[英]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.

相关问题 有没有一种方法可以强制从父组件重新渲染子组件,而无需在 React 中更改其道具? - Is there a way to force a re-render of a child component from the parent component without using changing its props in React? 反应:从渲染方法外部更新组件的道具而不使用状态 - React: update component's props from outside of render method without using state 如何更新使用ReactDOM.render()呈现的React组件的道具 - How to update props of React Component rendered using ReactDOM.render() React:将组件作为道具传递而不使用 this.props.children - React: Pass component as prop without using this.props.children 在 NextJS 中不使用 props 或 context 将脚本标签添加到 React 组件 - Add script tag to React component without using props or context in NextJS 如何在不使用道具的情况下创建反应布局组件? - How to create a react layout component without using props? 反应:不使用“ this”访问组件的最干净方法 - React: Cleanest way of accessing component without using “this” React-道具不会在整个组件中相同地更新 - React - props does not update in entire component the same React 组件未收到 Redux 商店更新的道具 - React component not receiving props on Redux store update 如何基于道具更新React组件状态 - How to update react component state based on props
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM