Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用输入文本作为数据进行POST请求_Javascript_Reactjs - Fatal编程技术网

Javascript 如何使用输入文本作为数据进行POST请求

Javascript 如何使用输入文本作为数据进行POST请求,javascript,reactjs,Javascript,Reactjs,我是新手,我正在尝试使用文本字段数据发出POST请求,有人能帮我保存输入并在按下按钮后发出请求吗 我尝试使用useRef(),这允许我获取数据,但我无法将其存储为数据对象,然后保存 当前我的数据持续存在,但是它持续存在一个空对象,并且状态未被更新 如果有人能帮忙,我将非常感激 下面是我的App.js课程 import React, { useState, useEffect, useRef, Component } from 'react'; import axios from "ax

我是新手,我正在尝试使用文本字段数据发出POST请求,有人能帮我保存输入并在按下按钮后发出请求吗

我尝试使用
useRef()
,这允许我获取数据,但我无法将其存储为数据对象,然后保存

当前我的数据持续存在,但是它持续存在一个空对象,并且状态未被更新

如果有人能帮忙,我将非常感激

下面是我的
App.js
课程

import React, { useState, useEffect, useRef, Component } from 'react';
import axios from "axios";

const api = axios.create({
    baseURL: "http://localhost:8080/artists"
});

class App extends Component {
    state = {
        artists: [],
        theArtistName: ""
    }

    constructor(props){
        super(props);
        this.getArtists()
    }

    //calling this method will allow artist array to be populated everytime an event occurs, e.g POST, PUT, DELETE
    getArtists = async () =>{
        let data = await api.get("/").then(({ data }) => data);
        this.setState({artists: data}) //setting our artists to be the data we fetch
    }

    createArtist = async () =>{
       let response = await api.post('/', {name: this.state.theArtistName})
        console.log(response)
        this.getArtists()
    }

    deleteArtist = async (id) =>{
        let data = await api.delete('/${id}')
        this.getArtists();
    }

    handleAddArtist = (event) =>{
        event.preventDefault()
        this.setState({
            theArtistName: event.target.value
        })
        const data = this.state.theArtistName
        console.log(data)

    }

    componentDidMount(){
        this.createArtist()

    }

    render(){
        // const {theArtistName} = this.state
        return(
            <>           
            <input type={Text} placeholder="Enter Artist Name" name="theArtistName"></input>
                <button onClick={this.createArtist}>Add Artist</button>
                    {this.state.artists.map(artist => <h4 key={artist.id}>{artist.name}
                <button onClick={() =>this.deleteArtist(artist.id)}>Delete artist</button></h4>)}
            </>
        )
        
    }

}


export default App;

import React,{useState,useffect,useRef,Component}从'React'导入;
从“axios”导入axios;
const api=axios.create({
基本URL:“http://localhost:8080/artists"
});
类应用程序扩展组件{
状态={
艺术家:[],
艺人姓名:“
}
建造师(道具){
超级(道具);
这个
}
//调用此方法将允许每次发生事件(例如POST、PUT、DELETE)时填充艺术家数组
getArtists=async()=>{
让data=wait-api.get(“/”),然后(({data})=>data);
this.setState({artists:data})//将我们的艺术家设置为我们获取的数据
}
createArtist=async()=>{
let response=wait-api.post('/',{name:this.state.theArtistName})
console.log(响应)
这个
}
deleteArtist=async(id)=>{
let data=wait api.delete('/${id}'))
这个.getArtists();
}
HandLeadDartList=(事件)=>{
event.preventDefault()
这是我的国家({
参与者名称:event.target.value
})
const data=this.state.theArtistName
console.log(数据)
}
componentDidMount(){
this.createArtist()
}
render(){
//const{theArtistName}=this.state
返回(
添加艺术家
{this.state.artists.map(artist=>{artist.name}
this.deleteArtist(artist.id)}>deleteArtist)}
)
}
}
导出默认应用程序;

首先,
useRef
是一个钩子,仅用于函数组件,不用于类组件。要在类组件中使用ref,请使用
React.createRef()

通常,HTML输入元素保持自己的状态。从呈现输入元素的React组件访问输入元素值的常用方法是通过向输入元素添加
onChange
侦听器和
value
属性,通过该组件控制输入元素的状态:

类应用程序扩展组件{
建造师(道具){
超级(道具);
this.state={artistName:”“};
this.handleArtistNameChange=this.handleArtistNameChange.bind(this);
}
handleArtistNameChange(事件){
this.setState({artistName:event.target.value});
}
render(){
报税表(
);
}
}
每当输入元素的值发生变化时,
App
组件将以输入的最新值在其状态下重新启动

以下是一个工作示例:


您可以阅读有关在React中使用表单元素的更多信息。

因为React异步更新状态,所以当您调用
HandLeadDartList
函数时,该更新状态事件可能会消失,因此您需要将事件中的值存储在变量中,如下所示:

handleAddArtist = (event) =>{
    event.preventDefault()
    const {value} = e.target
    this.setState({
        theArtistName: value
    })
}
componentDidUpdate(prevProps,prevState){
if(prevState.theArtistName!==this.state.theArtistName)
this.createArtist()
}
要检查状态更新,有一个生命周期方法,对于类组件称为
componentdiddupdate
,对于功能组件称为
useffect

[编辑]: 在
componentDidUpdate
中调用
this.createArtister()
,如下所示:

handleAddArtist = (event) =>{
    event.preventDefault()
    const {value} = e.target
    this.setState({
        theArtistName: value
    })
}
componentDidUpdate(prevProps,prevState){
if(prevState.theArtistName!==this.state.theArtistName)
this.createArtist()
}

因此,
createArtist
只有在
artistName
状态更改时才会触发。

此.setState
是一个异步函数,它将第二个参数作为回调。这应该能解决你的问题。i、 e

import React, { useState, useEffect, useRef, Component } from "react";
import axios from "axios";

const api = axios.create({
  baseURL: "http://localhost:8080/artists",
});

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      artists: [],
      theArtistName: "",
    };
  }

  //calling this method will allow artist array to be populated everytime an event occurs, e.g POST, PUT, DELETE
  getArtists = async () => {
    let data = await api.get("/").then(({ data }) => data);
    this.setState({ artists: data }); //setting our artists to be the data we fetch
  };

  createArtist = async () => {
    let response = await api.post("/", { name: this.state.theArtistName });
    console.log(response);
    this.getArtists();
  };

  deleteArtist = async (id) => {
    let data = await api.delete("/${id}");
    this.getArtists();
  };

  handleAddArtist = (event) => {
    event.preventDefault();
    this.setState(
      {
        theArtistName: event.target.value,
      },
      () => {
        this.createArtist();
      }
    );
  };

  componentDidMount() {
    this.getArtists();
  }

  render() {
    // const {theArtistName} = this.state
    return (
      <>
        <input
          type={Text}
          placeholder="Enter Artist Name"
          name="theArtistName"
        ></input>
        <button onClick={this.handleAddArtist}>Add Artist</button>
        {this.state.artists.map((artist) => (
          <h4 key={artist.id}>
            {artist.name}
            <button onClick={() => this.deleteArtist(artist.id)}>
              Delete artist
            </button>
          </h4>
        ))}
      </>
    );
  }
}

export default App;
import React,{useState,useffect,useRef,Component}来自“React”;
从“axios”导入axios;
const api=axios.create({
基本URL:“http://localhost:8080/artists",
});
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
艺术家:[],
艺人姓名:“,
};
}
//调用此方法将允许每次发生事件(例如POST、PUT、DELETE)时填充艺术家数组
getArtists=async()=>{
让data=wait-api.get(“/”),然后(({data})=>data);
this.setState({artists:data});//将我们的艺术家设置为我们获取的数据
};
createArtist=async()=>{
let response=wait api.post(“/”,{name:this.state.theArtistName});
控制台日志(响应);
这个.getArtists();
};
deleteArtist=async(id)=>{
让data=wait-api.delete(“/${id}”);
这个.getArtists();
};
HandLeadDartList=(事件)=>{
event.preventDefault();
这是我的国家(
{
参与者名称:event.target.value,
},
() => {
这个.createArtist();
}
);
};
componentDidMount(){
这个.getArtists();
}
render(){
//const{theArtistName}=this.state
返回(
添加艺术家
{this.state.artists.map((artist)=>(
{艺术家名称}
this.deleteArtist(artist.id)}>
删除艺术家
))}
);
}
}
导出默认应用程序;

如果有帮助,请告诉我。

redux表单使这非常容易。查看这里的文档,他不需要绑定他正在使用的arrow函数,它会自动绑定到最近的方法context@adel约书亚在问题中提供的密码是正确的,但是我的回答中没有提到这个例子,因为我没有使用箭头函数。嘿,Befeepilf谢谢你对我的问题的回答,我把它添加到了我的代码中,但是我仍然很难回答