如何在组件类上调用setTimeOut

问题描述 投票:0回答:2

在调用setTimeOut(Question,3000)后,我收到错误“无法将类称为函数”。 “问题”需要是一个类才能获得类接收的生命周期方法。

到目前为止我找到的唯一答案是在类上包含“extends React.Component”,我有。

import React from 'react';
import Question from './Question';

setTimeout(Question, 3000);


function Congratulations(props) {
    return(
        <div>
        <h1>Congraulations you are the champion.</h1>
        <h2>Your Score: {props.score}</h2>
    </div>
    )
}  
export default Congratulations;

问题组件类的前几行如下。

export default class Question extends React.Component {
constructor(props) {
    super(props);

我希望3秒后问题出现在DOM上。

reactjs function class settimeout
2个回答
0
投票

你可以在componentdidmount方法中使用并在3秒后为show设置状态。在render方法中,只有show为true才能渲染。

在构造函数方法中,创建一个show = false的状态。

在componentDidMount中你可以创建

setTimeOut(() => this.setState({ show: true}), 3000)

在render方法中,您可以使用该状态进行渲染

{
 show &&
  // render what you want
}

0
投票

超时不是你的问题,你只是没有Reacts设置代码。查看React-Dom's render method.您需要将设置代码包装在函数中,然后使用setTimeout触发该函数。即使是React函数组件,如果你直接调用它也不会做太多,就像setTimeout会做的那样。

© www.soinside.com 2019 - 2024. All rights reserved.