在没有形式的React中使用POST? [英] Using POST in React without form?
问题描述
让我说我这里有这个代码:
Lets say I have this code here:
getInitialState:function(){
return { food: 'Chinese' }
},
restaurants:function(){
return (<div><form method="post">
<p>I like <span name="food">{this.state.food}</span> food</p>
<button type="submit">Butane</button>
</form></div>);
},
到目前为止,我对POST的唯一体验是表单和输入字段。所以我想知道如何在没有使用更多静态内容的情况下做到这一点。
My only experience with POST so far has been with forms and input fields. So I would like to know how to do this without, using more static content.
在上面的例子中,我的内容不是从输入字段派生的。我想将状态变量(在本例中为中文
)放入POST请求中。
In the above example, I have content that isn't derived from an input field. I would like to put the state variable, in this case, Chinese
, into a POST request.
理想情况下,标有丁烷的按钮会将我的状态信息提交到我的POST中。并且span命名是为我的后端指定一个名称来读取它。
Ideally, the button labeled butane
submits the info from my state into my POST. And the span name is there to assign it a name for my back-end to read it from.
我如何重新安排此代码以在POST上下文中使用状态变量?
How would I re-arrange this code to enable use of the state variable in a POST context?
推荐答案
由于您正在使用React,因此您可能会开发一个不会重新加载的单页应用程序,也不会将用户引导到另一个位置。要执行POST请求,您需要异步 。其中一种方便的方法是使用 axios 。整个组件看起来像这样:
Since you're working with React, chances are you develop a single-page application that doesn't reload nor does it lead a user to another location. To perform a POST request then, you need to do it asynchronously. One of the convenient ways is to use axios for that. The whole component would look like this:
import React, { Component } from 'react';
import axios from 'axios';
class X extends Component {
constructor() {
super();
this.state = {
food: 'Chinese'
};
}
handleSubmit(event) {
const {
food
} = this.state;
event.preventDefault();
// do something with form values, and then
axios.post('https://your/api/endpoint', {
food // + any other parameters you want to send in the POST request
}).then(response => {
// do something with response, and on response
}).catch(error => {
// do something when request was unsuccessful
});
}
restaurants() {
return (
<div>
<form
method="post"
onSubmit={event => this.handleSubmit(event)}>
<p>I like <span name="food">{this.state.food}</span> food</p>
<button type="submit">Butane</button>
</form>
</div>
);
}
}
这篇关于在没有形式的React中使用POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!