【问题标题】:Invalid hook call, from Reactjs to Nextjs无效的钩子调用,从 Reactjs 到 Nextjs
【发布时间】:2022-02-12 15:48:16
【问题描述】:

我在 ReactJS 世界之外已经有一段时间了,我决定回来尝试一下 NextJS。但是我遇到了无效的挂钩调用问题。

我正在尝试将我的 ReactJS 项目转换为 NextJS 项目。我将以较短的格式显示代码,仅用于示例。

这是我的 Reactjs:

index.js

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

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';


class App extends Component {
  render() {
    return (
        <Router>
          <main>
            <Switch>
              <Route exact path='/' component={MainPage}/>
            </Switch>
          </main>
        </Router>
    );
  }
}

export default App;

MainPage.js

import React, { Fragment } from 'react';

import './MainPage.css';

const MainPage = () => {
    return (
        <Fragment>
            <div>
                  Hello There :-)
            </div>
       <Fragment>
    );
};

export default MainPage;

这是我的 Nextjs:

_app.js

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

index.js

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import MainPage from './components/MainPage';


class App extends Component {
  render() { **// not sure about the render**
    return (
        <Router>
          <main>
            <Switch> **// I think was switched to Routes**
              <Route exact path='/' component={MainPage}/> **// I think was switched to element**
            </Switch>
          </main>
        </Router>
    );
  }
}

export default App;

MainPage.js

import styles from '../styles/Home.module.css'

export default function Home() {
  return (
    <div className={styles.container}>    
      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
      </main>
    </div>
  )
}

【问题讨论】:

  • idk 出了什么问题,但是 NextJs 有一个内置的基于文件夹的路由系统。也许你可能想改用那个
  • 您可以删除所有路由逻辑,因为它是 Boa 所说的内置的 - nextjs.org/docs/routing/introduction - 您当前的 pages/index.js 代码应该用来自 MainPage.js 的代码替换文件

标签: javascript reactjs next.js


【解决方案1】:

你不需要在下一个 js 中反应路由器,因为它有一个 pages 文件夹,你创建的任何文件夹都将是你的路由,例如,如果你创建一个 about 文件夹和其中的 index.js,index.js 文件将在 /about 路由上显示给您;

对于主页,您可以在 pages 文件夹附近创建一个 components 文件夹,然后将 MainPage.js 移到那里,然后将其导入 pages 文件夹内的 index.js 中;

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2022-01-08
    • 2020-12-18
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2020-12-02
    相关资源
    最近更新 更多