Очистка проекта и перезагрузка xCode работали для меня.
Один из способов подойти к этому - отложить рендеринг потомка до момента монтирования родителя. Шаги будут выглядеть следующим образом:
componentDidMount
выполняет стороннюю инициализацию и изменяет флаг в родительском состоянии, вызывая повторную визуализацию родителя Полученный код будет выглядеть примерно так:
import React from "react";
import ReactDOM from "react-dom";
class ThirdPartyLib {
init(elementId) {
console.log(`initializing element: ${elementId}`);
this.element = document.getElementById(elementId);
this.element.style.color = "red";
}
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { initialized: false };
console.log("Parent's constructor");
}
render() {
console.log("rendering Parent");
return (
<div id="parent">
Parent: {this.props.name}
{this.state.initialized && (
<Child name="Sara" thirdPartyLib={this.state.thirdPartyLib} />
)}
</div>
);
}
componentDidMount() {
console.log("Parent is mounted");
const thirdPartyLib = new ThirdPartyLib();
thirdPartyLib.init("parent");
this.setState({ initialized: true, thirdPartyLib });
}
}
class Child extends React.Component {
constructor(props) {
super(props);
console.log(`Child ${this.props.name} constructor`);
console.log(
`Child knows stuff from thirdPartyLib: ${
this.props.thirdPartyLib.element.id
}`
);
}
render() {
console.log(`rendering Child: ${this.props.name}`);
return (
<div>
Child: {this.props.name}
<br />
ThirdPartyLib element id:
{this.props.thirdPartyLib.element.id}
</div>
);
}
componentDidMount() {
console.log(`Child ${this.props.name} is mounted`);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent name="Bob" />, rootElement);