React Post data onClick



错误:对象作为React子对象无效(found: object with keys){sds, id})。如果您打算呈现子集合,请使用数组。

import React, {Component} from 'react';
import axios from "axios";
class Post extends Component {
constructor() {
super();
this.state={
postData : "",
postResult : " "
}
}
onChangeHandler=(event)=>{
var mydata= event.target.value;
this.setState({postData:mydata})
}
onClickHandler=()=>{
axios.post('http://jsonplaceholder.typicode.com/posts',this.state.postData)
.then(response=>{
this.setState({postResult:response.data})
})
.catch(error=>{
alert("something wrong")
})
}
render() {
return (
<div>
<p>{this.state.postResult}</p>
<input onChange={this.onChangeHandler} type="text"/>
<button onClick={this.onClickHandler}>Post</button>
</div>
);
}
}
export default Post;

基于jsonplaceholder,您的response.data将是以下结构的对象:

{title: "myTitle", body: "myBody", id: 101} 

这样this.state.postResult将是一个对象,你不能传递一个对象来渲染,这会导致错误。相反,您可以从postResult中提取titlebody,例如:

render() {
const { title, body } = this.state.postResult
return (
<div>
<h1>Title: {title}</h1>
<p>Body: {body}</p>
<input onChange={this.onChangeHandler} type="text"/>
<button onClick={this.onClickHandler}>Post</button>
</div>
);
}

最新更新