我正在为我的react js应用程序创建CRUD,基本上发生的事情是当我添加或发布将要添加的数据,但是除非刷新页面,否则该表不会更新或显示所添加的最新数据。
这是我用于显示数据的代码
componentDidMount() {
axios.get('http://mylink')
.then(response => {
this.setState({students: response.data})
})
.catch(error => {
console.log('No data to be shown')
})
}
以及用于添加数据
handleAddData = () => {
axios({
url: 'http://mylink',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: {
students: students
}
})
我想发生的是,当添加数据时,表将自动更新而无需刷新。
帖子通常是用一个新元素制作的,确认后会更新该州的学生:
axios({
url: 'http://mylink',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data: newStudent // must receive this
})
.then( response => {
const { students } = this.state;
this.setState({students: [newStudent, ...students});
})