[英]How to make a POST request with input text as data React
I am new to react and I am trying to make a POST request using text field data, can anyone help me with how to store that input and make a request after a button is pressed.我是新手,我正在尝试使用文本字段数据发出 POST 请求,任何人都可以帮助我如何存储该输入并在按下按钮后发出请求。
I attempted to use useRef()
which allowed me to obtain the data however I was not able to store it as a data object to then persist.我尝试使用useRef()
来获取数据,但是我无法将其存储为数据 object 然后持续存在。
Currently my data persists, however it persists an empty object and the state is not being updated.目前我的数据仍然存在,但是它仍然存在一个空的 object 并且 state 没有被更新。
If anyone can help, I will really appreciate that.如果有人可以提供帮助,我将不胜感激。
Below is my App.js
class下面是我的App.js
class
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;
because react update state asynchronously so when you are invoking handleAddArtist
function which update state the event might be gone so you need to store the value from the event in variable like this:因为反应更新 state 是异步的,所以当你调用handleAddArtist
function 更新 state 事件可能会消失,所以你需要存储变量中的值:
handleAddArtist = (event) =>{
event.preventDefault()
const {value} = e.target
this.setState({
theArtistName: value
})
}
and to check state update there is a lifecycle method called componentDidUpdate
for class component and useEffect
for functional component.并检查 state 更新有一个生命周期方法componentDidUpdate
用于 class 组件和useEffect
用于功能组件。
[edit]: call this.createArtist()
in componentDidUpdate
like this: [编辑]:在componentDidUpdate
中调用this.createArtist()
,如下所示:
componentDidUpdate(prevProps,prevState){
if(prevState.theArtistName!==this.state.theArtistName)
this.createArtist()
}
so the createArtist
will fire only when theArtistName
state change.所以createArtist
只会在theArtistName
state 改变时触发。
this.setState
is an async function, it takes second argument as callback. this.setState
是一个异步 function,它需要第二个参数作为回调。 This should solve your problem.这应该可以解决您的问题。 ie IE
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;
Let me know if it helps.让我知道它是否有帮助。
First of all, useRef
is a hook only meant for function components and not for class components.首先, useRef
是一个钩子,仅适用于 function 组件,不适用于 class 组件。 For using Refs in class components use React.createRef()
.要在 class 组件中使用 Refs,请使用React.createRef()
。
Usually, HTML input elements maintain their own state.通常,HTML 输入元素维护自己的 state。 The usual way to access the value of an input element from a React component that renders it is to control the input element's state via this component by adding an onChange
listener and a value
attribute to the input element:从渲染它的 React 组件访问输入元素的值的常用方法是通过向输入元素添加onChange
侦听器和value
属性来通过此组件控制输入元素的 state:
class App extends Component{
constructor(props) {
super(props);
this.state = {artistName: ""};
this.handleArtistNameChange = this.handleArtistNameChange.bind(this);
}
handleArtistNameChange(event) {
this.setState({artistName: event.target.value});
}
render(){
return (
<input
type="text"
value={this.state.artistName}
onChange={this.handleArtistNameChange}
/>
);
}
}
Whenever the value of the input element changes the App
component will rerender with the most up-to-date value of the input in its state.每当输入元素的值发生更改时, App
组件将使用其 state 中的最新输入值重新呈现。
Here is a working example:这是一个工作示例:
You can read more on using form elements in React here .您可以在此处阅读有关在 React 中使用表单元素的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.