【发布时间】:2019-10-12 04:09:04
【问题描述】:
我正在关注如何将文本发布到 django rest api 服务器的教程。每个教程都说要使用 state 和 this.setState 来更新 api 表单并将其发送到服务器。但是经过大约两天的尝试,我无法弄清楚是什么问题。
我已经尝试过使用构造函数,将 App 设置为类而不是函数,并且在我能找到的每个教程中都搞砸了。我对此真的很陌生,所以这可能很明显。
这是我的 App.jsx
import React from 'react';
import './scss/sass.scss';
import './scss/customBootstrap.scss';
import 'react-bootstrap';
import axios from 'axios';
function App() {
var fontWeight = {
fontWeight: 'bold',
};
var backgroundColor = {
backgroundColor: 'chartreuse'
};
function onClick() {
console.log("Sending a GET API Call !!!");
axios.get('http://127.0.0.1:8000/api')
.then(res => {
console.log(JSON.stringify(res))
})
};
var state = { description: '' }
function handleChange(e) {
this.setState({
[e.target.id]: e.target.value
})
};
function handleSubmit(e) {
e.preventDefault();
console.log(this.state);
let form_data = new FormData();
form_data.append('description', this.state.description);
let url = 'http://localhost:8000/api/';
axios.post(url, form_data, {
headers: {
'content-type': 'multipart/form-data'
}
})
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err))
};
return (
<React.Fragment>
<div className="container">
<div className="row">
</div>
</div>
<div className="container">
<div className="row" style={backgroundColor}>
<div className="col">
<form className="search-bar">
<input type="text" placeholder="Search"/>
<button type="submit"></button>
</form>
</div>
</div>
</div>
<div className="container">
<div id="post" className="row">
<div className="col">
<form className="user-post">
<textarea className="user-post" placeholder="Write a post here"></textarea>
<button type="submit"></button>
</form>
</div>
</div>
<div id="content" className="row">
<p className="link-text">Content will be here</p>
</div>
//this is a get request that somehow works fine compared to the post request
<div>
<button type="button" onClick={onClick}>Send GET /products</button>
</div>
//this is the tutorial text input form im trying to make work
<form onSubmit={handleSubmit}>
<p>
<input type="text" placeholder='Description' id='description' value={this.state.description} onChange={handleChange} required/>
</p>
<input type="submit"/>
</form>
<div id="feedback" className="row">
<div className="col">
<form className="feedback" name="feedback">
<textarea maxLength="335" className="feedback" placeholder="Write your feedback here"></textarea>
<button type="submit"></button>
</form>
</div>
</div>
</div>
<footer>
</footer>
</React.Fragment>
);
}
export default App;
最后应该发生的是它将输入的文本发送到api,但是当我尝试从浏览器发送文本数据时,浏览器给我:“TypeError:无法读取未定义的属性'setState'”。
【问题讨论】:
标签: javascript reactjs create-react-app