在 componentDidMount 中渲染一个新组件 - React

Rendering a new component inside componentDidMount - React

我将不得不在加载所有预期组件后渲染一个新组件。我将需要一个超时,基于该超时必须呈现新组件。所以这个新组件必须在页面加载 5 分钟后显示。 我需要渲染一个名为 new_component 的组件,它扩展了 React.component

public componentDidMount(): void {
      if (visited) {
      setTimeout(() => {
        console.log('Reached the timeout')
        //Render the new conponent here. (Not sure how to call the render function of another component here)
      }, timeout);
    }

谁能帮我调用 componentDidMount 里面 new_component 的渲染函数。我试过 new_component.render()。但这似乎行不通。

您可以使用 state 来跟踪它。

componentDidMount() {
    setTimeout(() => {
        this.setState({ showNewComponent: true })
    })
}

render中:

render() {
    if (this.state.showNewComponent) {
         return <NewComponent />
    }
    return null
}

您可以使用此代码,等待然后渲染新代码:

cosnt FIVE_MIN = 5 * 60 * 1000

class Example {
  this.state = { isShowComponent: false }
  timer 

  componentDidMount() {
    this.timer = setTimeout(() => {
      this.setState({ isShowComponent: true })
    }, FIVE_MIN) 
  }

  componentWilllUnmount() {
    clearTimeout(this.timer)
  }

  render() {
    if (this.state.isShowComponent) return <NewComponent />

    return <Component />
  }
}

:)

您可以根据您的状态渲染您的组件。

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isTimeout: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    this.checkTimeout = setTimeout(() => { 
      this.setState(() => ({isTimeout: true}))
    }, 500);
  }
  componentWillUnmount() {
    // clean it up when the component is unmounted.
    clearTimeout(this.checkTimeout);
  }
  render () {
    if (isTimeout) {
        return (k<h1>time is running out</h1>)
    }

    return (<h1>hello world.</h1>)
  }
}