您好,我是 ReactJS 平台的学生开发人员。我之前在 render 方法中使用了类组件,但现在我正在学习钩子(Hook),函数组件对于它来说非常重要,就像每个 Reactjs 开发人员都知道的那样。我在使用嵌套组件时遇到问题,遇到如下错误:
index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it
你能帮我解决这个问题吗?如何在返回部分中有效地使用无状态函数组件?
我的示例嵌套组件代码:
import React, {useContext} from 'react';
import { BookContext } from '../../contexts/BookContext';
import BookDetails from './BookForm';
const BookList = (props) => {
const {books} = useContext(BookContext);
const emptyBooks = ()=>{
return (
<div className="empty">
No books to read. Let's read now. You are free!
</div>
)
}
const notEmptyBooks=()=>{
return (
<div className="book-list">
<ul>
{books.map(book=>{
return (
<BookDetails books={books} key={book.id}></BookDetails>
)
})}
</ul>
</div>
)
}
// it does not work. I think error is here
return books.length>0?()=>emptyBooks:()=>notEmptyBooks
}
export default BookList;
最佳答案
您需要调用这些函数。在原始代码中,从技术上讲,您只是使用 () => emptyBooks
返回函数定义。所以你的假设是正确的,错误发生在那里。
尝试以下代码片段:
return books.length > 0 ? emptyBooks() : notEmptyBooks()
希望这会有所帮助!
关于javascript - 嵌套函数组件ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814367/