You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将React时钟组件从index.js迁移至App.js并解决显示问题?

解决方案

一、先修复原代码的核心错误

原Clock组件的render方法里,传递给Anotherwan的time属性存在写法错误:

// 错误写法
<Anotherwan time={this.time.date} />
// 正确写法
<Anotherwan time={this.state.time} />

this.state.time才是你在构造函数中定义的状态值,this.time.date是不存在的属性,这是导致页面无内容的直接原因。

二、迁移组件到App.js并简化index.js

1. 创建/修改App.js

把Clock类组件和Anotherwan函数组件全部迁移到App.js,并让App作为根组件渲染Clock:

import React from 'react';

function Anotherwan(props){
  return (
    <div>
      <h1> Time: {props.time.toLocaleTimeString()}</h1>
    </div>
  );
}

class Clock extends React.Component{
  constructor(props){
    super(props);
    this.state = {time: new Date()};
  }

  componentDidMount(){
    this.TimerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount(){
    clearInterval(this.TimerID);
  }

  tick (){
    this.setState({
      time: new Date()
    })
  }

  render (){
    return <Anotherwan time={this.state.time} />
  }
}

function App() {
  return <Clock />;
}

export default App;

2. 简化index.js

现在index.js只需要负责初始化React根节点并渲染App组件即可:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

三、额外优化建议(可选)

如果想进一步简化代码,可以把Clock组件改成函数式组件+hooks的写法,替代类组件:

import React, { useState, useEffect } from 'react';

function Anotherwan(props){
  return (
    <div>
      <h1> Time: {props.time.toLocaleTimeString()}</h1>
    </div>
  );
}

function Clock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(timerID); // 组件卸载时清除定时器
  }, []);

  return <Anotherwan time={time} />;
}

function App() {
  return <Clock />;
}

export default App;

内容的提问来源于stack exchange,提问作者Domzxc23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:03:23