[英]How to rerender a React component once mounted without calling setState in componentDidMount
I have a react component wrapped in a HOC that passes props to the wrapped child. 我有一个包装在HOC中的react组件,可将道具传递给包裹的孩子。 When the child's constructor is called it does some work and then it executes a callback passed down in props from the HOC.
调用子级的构造函数时,它将执行一些工作,然后执行从HOC传递到props中的回调。 This callback updates properties in the HOC constructor (definitions)(I think this is the correct language).
此回调更新HOC构造函数(定义)中的属性(我认为这是正确的语言)。 The HOC then uses the updated definitions to setup subscriptions for both the HOC and its wrapped child.
然后,HOC使用更新的定义为HOC及其包装的子项设置订阅。
The reason I am doing this is the child receives props from its parent that contains a dynamic array of objects that requires subscriptions while the component is mounted and there is no way to know what these subscriptions are when the HOC is instantiated. 我这样做的原因是,子级从其父级接收道具,该父级包含一个动态对象数组,在安装组件时需要订阅,并且在实例化HOC时无法知道这些订阅是什么。
The HOC is calling setState, which rerenders the child, however, I understand this is an anti-pattern. HOC正在调用setState,该方法将释放孩子,但是,我知道这是一种反模式。 How could I solve this?
我该如何解决?
HOC HOC
const HOCComponent= function HOCComponent(config) {
return function returnWrapped(Wrapped) {
return class Wrapper extends Component {
constructor(props) {
this.handleData = this.handleData.bind(this)
this.data = {}
}
comonentDidMount() {
setSubscription(this.data, () => {
this.setState({
key: getData(),
})
})
}
handleData(data) {
this.data = data
}
render () {
<Wrapped handleData={this.handleData} />
}
}
}
}
CHILD 儿童
const Component class Wrapper extends Component {
constructor(props) {
// Stuff with props received from it's parent (not HOC)
props.handleData(props.data)
}
render() {
<div>Hello!</div>
}
}
You can use the forceUpdate
method. 您可以使用
forceUpdate
方法。
Within the component if you call this.forceUpdate()
the component will be re-rendered. 如果您在组件内调用
this.forceUpdate()
,则将重新呈现该组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.