我找不到解决方案的控制台错误

时间:2020-07-08 21:58:15

标签: reactjs react-router

我继续在控制台中收到以下错误。我尝试隐式返回这些组件,将它们设置为既定名称和默认导出,也将它们导入。任何建议或意见将不胜感激。

未捕获的不变变量:元素类型无效:预期为字符串(对于内置组件)或类/函数(对于复合组件),但得到了:对象。 检查“标题”的渲染方法

AppRouter组件:

path('post/<pk>/', ..., ...)

标题组件:

import React from 'react';
import { BrowserRouter, Route, Switch, Link, NavLink } from 'react-router-dom';
import AboutPage from '../components/AboutPage';
import ContactPage from '../components/ContactPage';
import ErrorPage from '../components/ErrorPage';
import Header from '../components/Header';
import HomePage from '../components/HomePage';

const AppRouter = () => (
    <BrowserRouter> 
        <div>
            <Header />
            <Switch>
                <Route path='/' component={HomePage} exact={true}/>
                <Route path='/about' component={AboutPage}/>
                <Route path='/contact' component={ContactPage}/>
                <Route component={ErrorPage}/>
            </Switch>    
        </div>   
    </BrowserRouter>
);

export default AppRouter;

3 个答案:

答案 0 :(得分:0)

像这样更改Header组件

import React from 'react';
import { NavLink } from 'react-router-dom';

const Header = () => {
return (
    <div>
        <h1>FRD</h1>
        <NavLink to='/' activeClassName='is-active' exact={true}>Home</NavLink>
        <NavLink to='/about' activeClassName='is-active'>About</NavLink>
        <NavLink to='/contact' activeClassName='is-active'>Contact</NavLink>
    </div>
);
}
export default Header;

答案 1 :(得分:0)

对类及其功能有很好的了解,但首先要了解组件。 https://reactjs.org/docs/components-and-props.html#functional-and-class-componentshttps://medium.com/@leannezhang/curly-braces-versus-parenthesis-in-reactjs-4d3ffd33128f 然后您将了解发生了什么。

    const Header = () => {
return (
    <div>
        <h1>FRD</h1>
        <NavLink to='/' activeClassName='is-active' exact={true}>Home</NavLink>
        <NavLink to='/about' activeClassName='is-active'>About</NavLink>
        <NavLink to='/contact' activeClassName='is-active'>Contact</NavLink>
    </div>
);
}

答案 2 :(得分:0)

尝试更改以下内容:

const Header = () => (
    <div>
        <h1>FRD</h1>
        <NavLink to='/' activeClassName='is-active' exact={true}>Home</NavLink>
        <NavLink to='/about' activeClassName='is-active'>About</NavLink>
        <NavLink to='/contact' activeClassName='is-active'>Contact</NavLink>
    </div>
);

function Header() {
  return (  
      <div>
          <h1>FRD</h1>
          <NavLink to='/' activeClassName='is-active' exact={true}>Home</NavLink>
          <NavLink to='/about' activeClassName='is-active'>About</NavLink>
          <NavLink to='/contact' activeClassName='is-active'>Contact</NavLink>
      </div>);
}

或者在AppRouter中尝试以下操作。

<BrowserRouter> 
        <div>
            {Header}
            <Switch>
....