简体   繁体   中英

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. When the child's constructor is called it does some work and then it executes a callback passed down in props from the HOC. This callback updates properties in the HOC constructor (definitions)(I think this is the correct language). The HOC then uses the updated definitions to setup subscriptions for both the HOC and its wrapped child.

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.

The HOC is calling setState, which rerenders the child, however, I understand this is an anti-pattern. How could I solve this?

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.

Within the component if you call this.forceUpdate() the component will be re-rendered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM