修复React错误:函数不能作为React子元素问题求助
React项目POST请求相关错误修复方案
问题背景
学习React教程时,添加POST请求后出现两个异常:
- 页面报错「Functions are not valid as a React child」
- 控制台提示
fetch aborted,此前提交事件功能正常,这是第一个React Web应用,已查阅相关问题未找到适配方案。
错误原因及修复步骤
1. 「Functions are not valid as a React child」错误修复
原因:select标签的value和onChange属性被错误写在标签闭合之后,React会将这些属性代码当作子元素尝试渲染,而onChange是函数,React不允许直接渲染函数,因此触发该错误。
修复代码:将属性移至select起始标签内:
<select value={author} onChange={(e) => setAuthor(e.target.value)}> <option value="mario">Mario</option> <option value="yoshi">Yoshi</option> </select>
2. fetch aborted错误修复
原因:提交按钮放在了form标签外部,点击按钮时不会触发form的onSubmit事件,反而触发页面默认刷新行为,导致正在进行的fetch请求被中止。
修复代码:将按钮移至form标签内部,并明确按钮类型为submit:
<form onSubmit={handleSubmit} > <!-- 其他表单元素保持不变 --> <select value={author} onChange={(e) => setAuthor(e.target.value)}> <option value="mario">Mario</option> <option value="yoshi">Yoshi</option> </select> <!-- 按钮移到form内部 --> { !isLoading && <button type="submit">Add blog</button> } { isLoading && <button type="submit" disabled>Adding blog...</button> } </form>
完整修复后的Create.js代码
import { useState } from "react"; const Create = () => { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [author, setAuthor] = useState('mario'); const [isLoading, setIsLoading] = useState(false); //Submit events const handleSubmit = (e) => { e.preventDefault(); const blog = { title, body, author }; setIsLoading(true); //POST request fetch("http://localhost:8000/blogs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(blog), }).then(() => { console.log("new blog added"); setIsLoading(false); }) } return ( <div className="create"> <h2>Add a new blog</h2> {/* Input form */} <form onSubmit={handleSubmit} > <label>Blog title</label> <input type="text" required value={title} onChange={(e) => setTitle(e.target.value)} /> <label>Blog body</label> <textarea required value={body} onChange={(e) => setBody(e.target.value)} ></textarea> <label>Blog author</label> {/* Blog author */} <select value={author} onChange={(e) => setAuthor(e.target.value)}> <option value="mario">Mario</option> <option value="yoshi">Yoshi</option> </select> {/* Button */} { !isLoading && <button type="submit">Add blog</button> } { isLoading && <button type="submit" disabled>Adding blog...</button> } </form> <p>{ title }</p> <p>{ body }</p> <p>{ author }</p> </div> ); } export default Create;
内容的提问来源于stack exchange,提问作者Felix Songwe
相关产品推荐
相关产品推荐

