反应 Post 数据 onClick

React Post data onClick

Error: Objects are not valid as a React child (found: object with keys {sds, id}). If you meant to render a collection of children, use an array instead.

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>
    );
}