我试图通过在组件方法中使用fetch api从本地服务器获取一些数据。单击按钮后,将触发在父组件上下文中定义的处理程序方法来获取数据并更新当前组件的状态,因此其子项为props(包含输入和提交按钮的组件),但是我收到了错误。
NewComment.js
class NewComment extends Component {
render()
{
return (
<DivNewComment>
{
this.props.accessToken ?
//textarea
<CommentTextarea
name="commentContentValue"
onChange={this.props.handleCommentValueChange} /> :
<div className="alert alert-warning">
<span
onClick={this.props.handleToggleLoginModal} >
Login required
</span>
</div>
}
{
this.props.accessToken &&
<div className="comment-options">
<label className="score-title">score</label>
<input className="score-input"
name="commentScoreValue"
onChange={this.props.handleCommentValueChange} />
<SubmitButton onClick={this.props.handleNewComment}>Submit</SubmitButton>
</div>
}
</DivNewComment>
);
}
}
Post.js
class Post extends Component {
constructor(props)
{
super(props);
this.state = {
commentContentValue: '',
commentScoreValue: '',
};
this.handleNewComment = this.handleNewComment.bind(this);
this.handleCommentValueChange = this.handleCommentValueChange.bind(this);
}
handleNewComment(e)
{
if (this.state.commentContentValue.trim() !== '')
if (!isNaN(parseInt(this.state.commentScoreValue)) && parseInt(this.state.commentScoreValue) >= 1 && parseInt(this.state.commentScoreValue) <= 10) { //simple score range validator
const headers = JSON.stringify({
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.accessToken}`,
});
const body = JSON.stringify({
content: this.state.commentContentValue,
score: this.state.commentScoreValue,
});
const request = new Request("http://localhost:8000/api/posts/1/comments", { //error issues here
method: "POST",
body,
headers,
});
fetch(request)
.then(response => console.log(response))
.catch(e => console.log(e));
}
}
handleCommentValueChange(e)
{
this.setState({
[e.target.name]: e.target.value,
});
}
render()
{
return (
<div>
<NewComment
accessToken={this.props.accessToken}
handleCommentValueChange={this.handleCommentValueChange}
handleNewComment={this.handleNewComment} />
</div>
);
}
}
我在控制台上看到了这个:
TypeError: Failed to construct 'Request': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'
答案 0 :(得分:0)
headers参数必须是标题的实例(https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers)。
只需使用:
const headers = new Headers({
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${this.props.accessToken}`,
});