I wrote a global prompt component, and manual calls are all normal, but when I call the global component in the componentDidMount in the page component, ReactDOM.render returns null, but changing the call to asynchronous or other calls returns an instance of Container. I don"t know why, ask for a big answer! To simplify the problem, the code is as follows
componentDidMount(){
const div=document.createElement("div");
const container=ReactDOM.render(<Container />,div)
document.body.appendChild(div);
console.log(container)
}
the Container code is as follows
import Hint from "./hint";
import React,{Component} from "react";
import {CSSTransition,TransitionGroup} from "react-transition-group"
class Container extends Component{
constructor(props){
super(props);
this.state={
message:[]
}
this.addMsg=this.addMsg.bind(this)
this.createKey=this.createKey.bind(this)
this.removeMsg=this.removeMsg.bind(this)
}
addMsg(msg){
let { message }=this.state;
msg.key=this.createKey();
message.push(msg);
this.setState({message});
console.log(message)
if(msg.duration>0){
let autoClose=setTimeout(_=>{
this.removeMsg(msg.key);
clearTimeout(autoClose)
}, msg.duration)
}
return ()=>{
this.removeMsg(msg.key)
}
}
removeMsg(key){
this.setState(prevState=>({
message:prevState.message.filter(msg=>{
console.log(msg.key===key)
if(msg.key===key){
if(msg.onClose){msg.onClose()}
return false
}
console.log(123)
return true
})
}),()=>{
console.log(this.state)
})
}
createKey(){
const { message }=this.state;
return `${new Date().getTime()}-${message.length}`
}
render(){
return(
<TransitionGroup>
{
this.state.message.map(msg=>(
<CSSTransition
key={msg.key}
timeout={300}
classNames="msg"
>
<Hint {...msg} close={this.removeMsg} />
</CSSTransition>
))
}
</TransitionGroup>
)
}
}
export default Container
Thank you all!