【发布时间】:2021-07-23 21:11:32
【问题描述】:
我正在使用 react 和 fetch 向我的本地 json 服务器提交发布请求。目标是在表单上提交“评论”并将其添加到 json 服务器。我的 json 文件似乎没有更新。我做错了什么?
import React, { Component } from 'react'
import './commentform.css';
class CommentForm extends Component {
handleSubmit = (e) => {
e.preventDefault()
console.log('submitted')
}
render(){
fetch('http://localhost:3001/comments', {
method: 'POST',
body: JSON.stringify(this.state)
}).then(function(response) {
console.log(response)
return response.json()
})
return (
<div>
<h1>What is your favorite breed?</h1>
<form onSubmit={this.handleSubmit}>
<label>Answer: </label><br/>
<textarea type="text" name="body"/><br/>
<input type="submit"/>
</form>
</div>
)
}
}
export default CommentForm
【问题讨论】:
-
您没有处理 textarea 文本更改并将值设置为 state。而且,fetch 必须在 handleSubmit 中,而不是在 render 函数中。