首页 > 解决方案 > 如果页面在 ReactJS 中,如何让应用在点击时刷新?

问题描述

我有一个应用程序,它基本上是一个导航栏,其中包含一些指向其他页面的链接,这些页面显示在它的正下方。一些页面从数据库中提取信息,或者在这种情况下,具有从数据库中删除信息的功能。按钮起作用并且确实删除了信息,但是为了刷新页面上显示的数据,我必须切换到导航栏上的另一个页面,然后返回到我希望更新的页面。

AdminApp.js(为便于阅读而缩短)

import React, { Component } from 'react';
import {
  Row, Container, Col, Form,
} from 'reactstrap';
import AdminDashboard from './AdminDashboard';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import ViewStudents from './ViewStudents';
import withAuth from './withAuth'; 


class AdminApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dropdownOpen: false
    }    
  }  

  render() {
    return (
      <Container>
        <Router>
          <Form>
            <div>
              <nav  className="navbar navbar-expand-lg navbar-light">
            <ul className="navbar-nav mr-auto">
            <li><Link to={'/viewstudents'}>View Students</Link></li>
            <li><Link to={'/viewgroups'}>Groups</Link></li>
            </ul>
            </nav>
            <hr />
          <Switch>
              <Route exact path='/' component={AdminDashboard} />
              <Route path='/viewstudents' component={ViewStudents} />
              <Route path='/viewgroups' component={ViewGroups} />
          </Switch>     
            </div>
          </Form>
        </Router>
      </Container>
    );
  }
}

export default withAuth(AdminApp);

如果我想在下面的代码中使用“handleSubmit()”函数,该函数可以正常从数据库中删除用户,我按下删除按钮并删除它们,但页面不会更新,直到我切换到另一个页面(假设是视图组),然后返回到它,然后显示没有被删除学生的表格。

import React, { Component } from "react";
import {
  Row,
  Container,
  Col,
  Form,
  FormGroup,
  Label,
  Input,
  Button,
  FormText,
  FormFeedback,
  CustomInput
} from "reactstrap";


class ViewStudents extends Component {
  constructor(props) {
    super(props);

    this.state = {
      students: [],
      year: year,
      term: term,
      IDs: [],
      checked: false
    }
    //this.fetch = this.fetch.bind(this)
    //this.getStudents = this.getStudents.bind(this)
    this.handleDelete = this.handleDelete.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillMount() {
    fetch("http://10.171.204.211/GetStudents/", {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        year: this.state.year,
        term: this.state.term
      })
    })
    .then(response => {
      return response.json();
    })
    .then(data => {
      this.setState({
        students: data.map(item => ({
          firstName: item.fields.firstName,
          lastName: item.fields.lastName,
          UCFID: item.fields.UCFID,
          term: item.fields.term,
          year: item.fields.year,
          id: item.fields.authID,
        }))
      })

      console.log(this.state);
      console.log(this.state.students);
    })
    .catch( err => {
        console.log(err)
      })

  }

  handleDelete = event => {
    var arr = this.state.IDs
    arr.push(event.target.value)        
    this.setState({
      IDs: arr
  })
  }

  handleSubmit() {
    console.log(this.state);

    fetch("http://10.171.204.211/DeleteStudent/", { ///////// change 
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(this.state)
    })

    this.props.history.go('/AdminApp');
  }

  renderTableData() {
    //this.getStudents(this.state.year, this.state.term);
    return this.state.students.map((student, index) => {
       const { firstName, lastName, UCFID, term, year, id } = student //destructuring
       return (
          <tr>
             <td>{firstName}</td>
             <td>{lastName}</td>
             <td>{UCFID}</td>
             <td>{term}</td>
             <td>{year}</td>
             <td><label>
                    <input type="checkbox" name={id} value={id} 
                    onChange={this.handleDelete.bind(this)} />
                </label></td>
          </tr>
       )
    })
  }

  render() {
    return (
      <Container>
        <Form className="SDForm">
          <Col  className="SDForm">
            <h1 className="mainTitles">View Students</h1>
          </Col>
          <div>
          <table id='projects'>
               <tbody>
               <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>UCFID</th>
                <th>Term</th>
                <th>Year</th>
                <th>Delete</th>
               </tr>
               {this.renderTableData()}
               </tbody>
            </table>
          </div>
          <Button onClick={this.handleSubmit}>Delete</Button>
        </Form> 
      </Container>
    );
  }
}

export default ViewStudents;

我怎样才能让它在按下删除按钮时自动重新加载页面?我试过使用 this.props.history.push('/viewstudents') 但它不起作用,因为该页面显示在 AdminApp 页面中。我对反应还很陌生,所以我无法弄清楚。

标签: javascriptreactjspage-refresh

解决方案


当您在视图中使用状态,并在删除后使用 this.setState({...}) 更新状态。React 会自动重新渲染表格。

在您的handleDelete功能中执行此操作

  handleDelete = event => {
    var arr = this.state.IDs
    arr.push(event.target.value)        
    this.setState({
      IDs: arr
  })
   this.setState({students:...}) //set the new data, either update the students array with a new one or fetch the data and update the state again
  }

推荐阅读