嗨,我是使用react和axios的新手。我已经尝试了简单用户CRUD的代码,当我成功更新数据时,页面将重定向到用户索引(使用this.props.history.push)。问题是数据没有立即刷新(索引用户中的数据未更新),需要刷新页面以正确显示数据。我已经尝试了调试,然后是componentDidMount,构造函数,渲染再次正确调用,但我看到axios中的问题获取用户方法仍然返回旧数据。如何解决?谢谢。
这是我的IndexUser.js
// IndexUser.js
import React, { Component } from 'react';
import UserService from './UserService';
import axios from 'axios';
import UserRow from './UserRow';
class IndexUser extends Component {
constructor(props) {
super(props);
this.state = {value: '', users: ''};
this.addUserService = new UserService();
}
componentDidMount(){
axios.get('http://localhost:4200/users')
.then(response => {
this.setState({ users: response.data });
})
.catch(function (error) {
console.log(error);
})
}
userRow(){
if(this.state.users instanceof Object){
return this.state.users.data.map(function(object, i){
return <UserRow obj={object} key={i} />;
})
}
}
render() {
return (
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<td>User Id</td>
<td>Username</td>
<td>Password</td>
</tr>
</thead>
<tbody>
{this.userRow()}
</tbody>
</table>
</div>
);
}
}
export default IndexUser;
这是我的EditUser.js:
// EditUser.js
import React, { Component } from 'react';
import axios from 'axios';
import UserService from './UserService';
class EditUser extends Component {
constructor(props) {
super(props);
this.state={user_id: this.props.match.params.user_id, username:'', password:''};
this.UserService = new UserService();
this.handleUsername = this.handleUsername.bind(this);
this.handlePassword = this.handlePassword.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
axios.get('http://localhost:4200/users/edit/'+this.props.match.params.user_id)
.then(response => {
if(response.data instanceof Object){
for(var key in response.data.data){
for(var subKey in response.data.data[key])
{
this.setState({[subKey]:response.data.data[key][subKey]});
}
}
}
})
.catch(function (error) {
console.log(error);
})
}
handleUsername(event){
this.setState({username:event.target.value});
}
handlePassword(event){
this.setState({password:event.target.value});
}
handleSubmit(event) {
this.UserService.updateData(this.state.username,this.state.password,this.props.match.params.user_id);
event.preventDefault();
this.props.history.push('/index');
}
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<label>
Edit Username:
<input type="text" value={this.state.username} onChange={this.handleUsername} className="form-control"/>
</label><br/>
<label>
Edit Password:
<input type="password" value={this.state.password} onChange={this.handlePassword} className="form-control"/>
</label><br/>
<input type="submit" value="Update" className="btn btn-primary"/>
</form>
</div>
);
}
}
export default EditUser;
这是我的UserRow.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import UserService from './UserService';
class UserRow extends Component {
constructor(props) {
super(props);
this.addUserService = new UserService();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
this.addUserService.deleteData(this.props.obj.user_id);
}
render() {
return (
<tr>
<td>
{this.props.obj.user_id}
</td>
<td>
{this.props.obj.username}
</td>
<td>
{this.props.obj.password}
</td>
<td>
<Link to={"/edit/"+this.props.obj.user_id} className="btn btn-primary">Edit</Link>
</td>
<td>
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Delete" className="btn btn-danger"/>
</form>
</td>
</tr>
);
}
}
export default UserRow;
这是我的UserService:
//UserService.js
import axios from 'axios';
class UserService {
sendData(userId, username, password) {
axios.post('http://localhost:4200/users/add/user', {
userId: userId,
username: username,
password: password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
};
updateData(username,password, user_id){
axios.post('http://localhost:4200/users/update/'+user_id, {
username: username,
password: password
})
.then(res => this.setState({ users: res.data }))
.catch(err => console.log(err))
};
deleteData(user_id){
axios.get('http://localhost:4200/users/delete/'+user_id, {
})
.then(console.log('Deleted')).catch(err => console.log(err))
}
}
export default UserService;
这是我的用户路由服务器(使用express + pg-promise):
// userRoutes.js
var express = require('express');
var app = express();
var userRouter = express.Router();
// Require User model in our routes module
var pgp = require('pg-promise')(/*options*/);
var db = pgp('postgres://postgres:ragamp@localhost:5433/coba');
//Index User
userRouter.route('/').get(function (req, res) {
db.any('select * from public.\"User\" ORDER BY user_id')
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL Users'
});
})
.catch(function (err) {
});
});
//Insert User
userRouter.route('/add/user').post(function (req, res) {
db.none('INSERT INTO public.\"User\"(user_id, username, password) VALUES($1, $2, $3)', [req.body.userId, req.body.username, req.body.password])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Insert One Users with username' + req.body.username
});
})
.catch(error => {
// error;
});
});
//Get one/Edit User
userRouter.route('/edit/:user_id').get(function (req, res) {
db.any('select * from public.\"User\" where user_id = $1', [req.params.user_id])
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Retrieved ALL Users'
});
})
.catch(function (err) {
});
});
//Update User
userRouter.route('/update/:user_id').post(function (req, res) {
db.none('UPDATE public.\"User\" SET username = $1, password = $2 where user_id = $3', [req.body.username, req.body.password, req.params.user_id])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Update One Users with username ' + req.body.username
});
})
.catch(error => {
// error;
});
});
//Delete User
userRouter.route('/delete/:user_id').get(function (req, res) {
db.none('DELETE FROM public.\"User\" WHERE user_id = $1', [req.params.user_id])
.then(() => {
// success;
res.status(200)
.json({
status: 'success',
message: 'Delete One Users with username ' + req.params.user_id
});
})
.catch(error => {
// error;
});
});
module.exports = userRouter;