类状态扩展了React.Component {...}
class Mother extends React.Component { constructor(props) { super(props); this._isMounted = false; this.state = { ...this.state, children: [] }; this.createState = this.createState.bind(this); } createState = (x, y) => { let key = this.state.children.length; let newState = <State x={x} y={y} key={key} />; const { children } = this.state; const newChildren = R.clone(children); newChildren.push(newState); if (this._isMounted) { console.log("AQUIIQ"); this.setState({ children: newChildren }); } }; async componentDidMount() { console.log("Funfa"); this._isMounted = true; this.interval = setInterval(this.onTick, 1); } async componentWillUnmount() { // Remove this to see warning. console.log("FunfaII"); clearInterval(this.interval); } render() { return <div>{this.state.children}</div>; } } class App extends React.Component { constructor(props) { super(props); this.state = { mother: new Mother(), drawing: false, mouse: { x: 0, y: 0 } }; this.handleMouseMove = this.handleMouseMove.bind(this); this.handleStartDraw = this.handleStartDraw.bind(this); this.handleStopDraw = this.handleStopDraw.bind(this); this.handleClick = this.handleClick.bind(this); } handleMouseMove = e => { if (this.state.drawing) { this.setState({ mouse: { ...this.state.mouse, x: e.evt.layerX, y: e.evt.layerY } }); } }; handleStartDraw = e => { this.setState({ drawing: true }); }; handleStopDraw = e => { this.setState({ drawing: false }); }; handleClick = e => { if (!this.state.drawing) return; else { const { mouse } = this.state; this.setState({ mouse: { ...this.state.mouse } }); const { mother } = this.state; const newMother = R.clone(mother); newMother.createState(mouse.x, mouse.y); this.setState({ mother: newMother, mouse: { ...this.state.mouse } }); } }; render() { console.log(new Mother() ); return ( <div> <input type="button" value="Start Draw" onClick={this.handleStartDraw} /> <input type="button" value="Stop Draw" onClick={this.handleStopDraw} /> <Stage width={window.innerWidth} height={window.innerHeight} onContentClick={this.handleClick} onContentMouseMove={this.handleMouseMove} > <Layer ref="layer">{this.state.mother.children}</Layer> </Stage> </div> ); } }
render(,document.getElementById(“ root”));
如何调用componentDidMount来为应用程序类的母亲类别?为什么未调用componentDidMount来对Mother类进行调用。
问题:
构造函数的母亲不称为componentDidMount
在App类中使用new Mother()时出错。
我该如何解决?