[英]How to do React forceUpdate() to a child component?
I can force reload for a parent component with this.forceUpdate()
, but how to do it for a child component?我可以使用
this.forceUpdate()
强制重新加载父组件,但是如何为子组件执行此操作?
ie following react class methods:即以下反应 class 方法:
buttonClick = () => {
//This updates parent (this) component
this.forceUpdate();
//This causes runtime error ("..not a function in buttonClick...")
Rtable.forceUpdate();
}
render () {
<div>
<RTable />
</div>
}
If child component is not memoized then rendering its parent will render the child.如果子组件没有被记忆,那么渲染它的父组件将渲染子组件。
If child component is memoized , you could force update with its reference .如果子组件被记忆,你可以强制更新它的引用。
And of course, passing different properties to a child, changing its state, will re-render it.当然,将不同的属性传递给一个孩子,改变它的 state,会重新渲染它。
Changing the key will UNMOUNT the component, it is like making a conditional rendering on it.
更改密钥将卸载组件,就像在其上进行条件渲染一样。
Here is an example demonstating everything mentioned:这是一个演示所有提到的示例:
class Child extends React.Component {
componentDidMount() {
console.log("mounted");
}
render() {
console.log("rendered");
return <div>Child</div>;
}
}
class App extends React.Component {
state = {
counter: 0
};
childRef = React.createRef();
onClick = () => this.forceUpdate();
onCounter = () => this.setState({ counter: this.state.counter + 1 });
onRef = () => this.childRef.current.forceUpdate();
render() {
return (
<>
<Child key={this.state.counter} ref={this.childRef} />
<button onClick={this.onClick}>Render</button>
<button onClick={this.onCounter}>Update Key</button>
<button onClick={this.onRef}>Render with ref</button>
</>
);
}
}
<RTable key={some variable that changes between renders} />
As pointed out below this will cause unmount, which causes the child to lose its state and also run componentWillUnmount
, componentDidMount
and constructor
methods (which may be useful when you want to resubscribe).正如下面所指出的,这将导致卸载,这会导致子级丢失其 state 并且还会运行
componentWillUnmount
、 componentDidMount
和constructor
方法(当您想要重新订阅时可能很有用)。
Documentation https://reactjs.org/docs/glossary.html#keys文档https://reactjs.org/docs/glossary.html#keys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.