React Native中使用super(props)报错,请求修正代码
Hey there! Let's work through the issues in your code that are causing those VS Code hints and keeping your app from working as expected. I've broken down the fixes step by step:
1. You're Registering the Wrong Root Component
The biggest problem here is your AppRegistry line. Right now you're telling React Native to launch the Splash component directly, which skips your entire Main component (the one handling the screen switch logic).
Change this:
AppRegistry.registerComponent('App', () => Splash)
To this:
AppRegistry.registerComponent('App', () => Main)
This ensures your Main component (with the timer and state management) is the entry point for your app.
2. Fixing the super(props) Hint (Optional but Clean)
If VS Code is nagging you about super(props), it's because modern React (16.8+) doesn't require it in class components unless you need to access this.props directly in the constructor. You can simplify your code by ditching the constructor entirely and using class field syntax for state:
Instead of this:
constructor(props) { super(props); this.state = { CurrentScreen: 'Splash' }; console.log('Moving to next screen...'); setTimeout(()=>{ console.log('Done!'); this.setState({ CurrentScreen: 'Home' }); }, 3000) }
Do this (and move the timer to a lifecycle method where it belongs):
state = { CurrentScreen: 'Splash' }; componentDidMount() { console.log('Moving to next screen...'); setTimeout(() => { console.log('Done!'); this.setState({ CurrentScreen: 'Home' }); }, 3000); }
Putting the timer in componentDidMount follows React best practices—this lifecycle method is meant for side effects like timers or API calls, whereas the constructor should only handle basic initialization.
3. Double-Check Your Component Imports
Make sure your import paths match your file structure. If your Home component lives in a file named Home.js inside the components folder, your import should be:
import Home from './components/Home';
If you're using an index.js file in the components folder to export the Home component, your original import is fine—just confirm that setup is correct.
Full Corrected Code
Here's the cleaned-up version of your code with all the fixes applied:
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import Splash from './components/splash'; import Home from './components/Home'; // Adjust path if needed class Main extends Component { state = { CurrentScreen: 'Splash' }; componentDidMount() { console.log('Moving to next screen...'); setTimeout(() => { console.log('Done!'); this.setState({ CurrentScreen: 'Home' }); }, 3000); } render() { const { CurrentScreen } = this.state; return CurrentScreen === 'Splash' ? <Splash /> : <Home />; } } AppRegistry.registerComponent('App', () => Main);
These changes will make your app launch the Main component, show the Splash screen for 3 seconds, then switch to the Home screen—just like you intended.
内容的提问来源于stack exchange,提问作者Poornaka

