gpt4 book ai didi

reactjs - 为什么此代码会发出有关函数作为 React 子项无效的警告?

转载 作者:行者123 更新时间:2023-12-03 14:11:10 25 4
gpt4 key购买 nike

警告是:Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

render() {
return (
<div className="App">
<AppContext.Provider value={this.state}>
<Navbar> <!-- this is the line React gives warning about -->
<Route exact path="/">
Welcome to the Library Management System
</Route>
<Route exact path="/about">
The About Page
</Route>
<Route exact path="/new-books">
<NewBooks />
</Route>
<Route exact path="/my-account">
<MyAccount />
</Route>
</Navbar>
</AppContext.Provider>
</div>
);
}

这就是我的 Navbar.js 中的内容文件:

import React from 'react';
import { BrowserRouter as Router, Switch, Link } from 'react-router-dom';
import './Navbar.css';
import AppContext from "../AppContext";

class UserLoggedInMenu extends React.Component {
render() {
return (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link to="/my-account" className="nav-link">
My Account
</Link>
</li>
<li className="nav-item">
<Link to="/logout" className="nav-link">
Log Out
</Link>
</li>
</ul>
)
}
};

class UserLoggedOutMenu extends React.Component {
render() {
return (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link to="/my-account" className="nav-link">
Log In
</Link>
</li>
</ul>
)
}
};

export default class Navbar extends React.Component {
render() {
return (
<div id="Navbar">
<AppContext.Provider>
{(context) => (
<Router>
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container">
<Link to="/" className="navbar-brand">
Library Management System
</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>

<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link to="/new-books" className="nav-link">
New Books
</Link>
</li>
</ul>
{context.userLoggedIn ? <UserLoggedInMenu /> : <UserLoggedOutMenu />}
</div>
</div>
</nav>

<main className="container">
<Switch>
{this.props.children}
</Switch>
</main>
</Router>
)}
</AppContext.Provider>
</div>
);
}
}

React 似乎认为 <Navbar>被定义为一个函数,但显然它不是。

最佳答案

提供者不将函数视为子函数:

<AppContext.Provider>
{(context) => (

你想要一个消费者:

<AppContext.Consumer>
{(context) => (

将来,调试此问题的一种简单方法是开始删除组件,直到找到导致错误的组件。

关于reactjs - 为什么此代码会发出有关函数作为 React 子项无效的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com