React js CRUD-如何在不刷新的情况下添加数据时自动更新表

问题描述 投票:0回答:1

我正在为我的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
          }
        })

我想发生的是,当添加数据时,表将自动更新而无需刷新。

reactjs
1个回答
0
投票

帖子通常是用一个新元素制作的,确认后会更新该州的学生:

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});
}) 
© www.soinside.com 2019 - 2024. All rights reserved.