【问题标题】:Rendering a new component inside componentDidMount - React在 componentDidMount 中渲染一个新组件 - React
【发布时间】:2020-05-31 14:46:54
【问题描述】:

在加载所有预期的组件后,我将不得不渲染一个新组件。我将需要一个超时,基于该超时必须呈现新组件。所以这个新组件必须在页面加载 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()。但这似乎不起作用。

【问题讨论】:

    标签: reactjs render


    【解决方案1】:

    你可以按你的状态渲染你的组件。

    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>)
      }
    }
    

    【讨论】:

      【解决方案2】:

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

      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 />
        }
      }
      

      :)

      【讨论】:

        【解决方案3】:

        您可以使用state 进行跟踪。

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

        在render:

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

        【讨论】:

        • 我只需要一次。设置一次后在哪里重置。
        • 你可以随时this.setState({showNewComponent: false})
        猜你喜欢
        • 2019-06-18
        • 1970-01-01
        • 1970-01-01
        • 2021-06-07
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 2020-08-09
        • 2018-01-26
        相关资源
        最近更新 更多