这是我第一次使用react,我不知道如何保存和从数据库中获取数据。
我创建了两个主文件夹“frontend”和“backend”,在frontend中我有一个表单,代码如下:
class NewLead extends React.Component {
constructor(props) {
super(props);
this.state = {
newLead: {
lead: '',
company: '',
person: '',
age: '',
gender: '',
phone: '',
description: ''
},
genderOptions: ['Male', 'Female'],
}
this.handleInput = this.handleInput.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
}
handleInput(e) {
let value = e.target.value;
let name = e.target.name;
this.setState( prevState => ({ newLead :
{...prevState.newLead, [name]: value}}))
}
handleClearForm() {
this.setState({
newLead: {
lead: '',
company: '',
person: '',
age: '',
gender: '',
phone: '',
description: ''
},
})
}
setData() {
.......................
}
render() {
return (
<Input inputType={'text'}
title= {'Lead Name'}
name= {'lead'}
value={this.state.newLead.lead}
placeholder = {'* Lead Name'}
handleChange = {this.handleInput}
/>
<Input inputType={'text'}
title= {'Company Name'}
name= {'company'}
value={this.state.newLead.company}
placeholder = {'* Company Name'}
handleChange = {this.handleInput}
/>
<Input inputType={'text'}
title= {'Person Name'}
name= {'person'}
value={this.state.newLead.person}
placeholder = {'Person Name'}
handleChange = {this.handleInput}
/>
<Input inputType={'number'}
title= {'Age'}
name={'age'}
value={this.state.newLead.age}
placeholder = {'Age'}
handleChange={this.handleInput}
/>
<Select title={'Gender'}
name={'gender'}
options = {this.state.genderOptions}
value = {this.state.newLead.gender}
placeholder = {'Gender'}
handleChange = {this.handleInput}
/>
<Input inputType={'number'}
title= {'Phone'}
name={'phone'}
value={this.state.newLead.phone}
placeholder = {'Phone'}
handleChange={this.handleInput}
/>
<TextArea title={'Description'}
rows={5}
value={this.state.newLead.description}
name={'description'}
handleChange={this.handleInput}
placeholder={'Description'}
/>
<Button bsStyle="secondary" style={buttonStyle}
href="/leads"> «-- Back
</Button>
<Button bsStyle="primary" style={buttonStyle}
onClick={ () => this.setData() }> Add +
</Button>
<Button bsStyle="secondary" style={buttonStyle}
onClick={ () => this.handleClearForm() }> Clear
</Button>
);
}
现在,当我单击add按钮时,我希望数据保存在数据库中,那么我应该在setdata()函数中添加什么呢?
在backend文件夹中,controllers文件夹中有4个文件“leadeitemcontroller.js”:
const LeadItem = require('../models/LeadItem')
module.exports = {
async listAll() {
try {
const leads = await LeadItem.findAll();
return leads;
} catch (error) {
console.error("\nError in LeadItemController trying to list all leads \n\n", error);
}
},
async store(leadData) {
try {
const leadItem = await LeadItem.create({
lead: leadData.lead,
company: leadData.company,
person: leadData.person,
age: leadData.age,
gender: leadData.gender,
phone: leadData.phone,
description: leadData.description
});
return leadItem;
} catch (error) {
console.error("\nError in LeadsController trying to create a leadItem \n\n", error);
}
}
}
路由文件夹中的“leaditemroute.js”:
const express = require('express');
const router = express.Router();
const LeadItemController = require("../controllers/LeadItemController");
router.get('/', async (req, res) => {
const leads = await LeadItemController.listAll();
return res.json(leads);
});
router.post('/', async (req, res) => {
const { id, lead, company, person, age, gender, phone, description } = req.body;
const leadData = { id, lead, company, person, age, gender, phone, description }
const lead = await LeadItemController.store(leadData);
if(!lead){
return res.status(400).json({ error: 'Fail to create lead' });
}
return res.send(lead);
});
module.exports = router;
模型文件夹中的“leaditem.js”:
const { Model , DataTypes } = require('sequelize');
class LeadItem extends Model {
static init(sequelize) {
super.init({
id : DataTypes.INTEGER,
lead: DataTypes.STRING(50),
company: DataTypes.STRING(50),
person: DataTypes.STRING(50),
age: DataTypes.INTEGER,
gender: DataTypes.STRING(50),
phone: DataTypes.INTEGER,
description: DataTypes.STRING
}, {
sequelize,
tableName: 'LeadItem'
});
}
}
module.exports = LeadItem;
最后,“server.js”文件如下所示:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const routes = require('./app/routes/index');
require('./app/database'); //Initialize database
const app = express();
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(routes);
const serverPort = 8000;
app.listen(serverPort, async () => {
console.log(`\nServer started on port ${serverPort}.\n`);
});
所以我能处理这个还是把一切都搞砸了?
暂无答案!
目前还没有任何答案,快来回答吧!