CoreUI 进行 API 次调用

CoreUI Make API Calls

我已经创建了一些基本的初学者 React 应用程序。但现在我想尝试使用模板“core-ui”。

https://github.com/coreui/coreui-free-react-admin-template

我想向一些外部端点发出请求并检索一些数据,但我不确定在哪里做。

这是我自己完成的:

import React from 'react';
import RowCreator from './RowCreator';


class DisplayCountries extends React.Component {

    constructor(props){
        super(props);
        this.state = {countries:[],
                      countriesClone:[]
        };
    }

    componentDidMount() {
        const axios = require('axios');
        const url = 'http://localhost:8080/demo/api/countries';
        axios.get(url).then(res=>{
            console.log(res.data);
            this.setState({countries:res.data,
                           countriesClone:res.data});

        }).catch(error=>{
            console.error('Error', error);
        })
      }

    handleOnChange(event){
        var filteredString = event.target.value;
        var filteredCountries = [];

        for(var country of this.state.countries){
            if(country.cioc.toLowerCase().indexOf(filteredString.toLowerCase())>=0 ||
                country.name.toLowerCase().indexOf(filteredString.toLowerCase())>=0 ||
                country.capital.toLowerCase().indexOf(filteredString.toLowerCase())>=0 ||
                country.region.toLowerCase().indexOf(filteredString.toLowerCase())>=0 ||
                country.subregion.toLowerCase().indexOf(filteredString.toLowerCase())>=0 ){
                    filteredCountries.push(country);
            }
        }

        this.setState({countriesClone:filteredCountries});
    }


    render(){

        return (<div>
                    <div className="headerBox">
                        <div className="row">
                            <div className="col-sm-12 text-center">
                                <h1>Search Countries</h1>
                            </div>
                        </div>
                        <div className="row">
                            <div className="col-sm-12 text-center">
                                <h3>Demo to filter the list of countries</h3><br/>
                            </div>
                        </div>
                    </div>

                    <div className="searchBox">
                        <div className="row text-right">
                            <div className="col-sm-3"/>
                            <div className="col-sm-6 text-center">
                             <br/><input type="text" className="form-control input-lg" placeholder="Search any field by name" onChange={this.handleOnChange.bind(this)}/><br/>
                            </div>
                            <div className="col-sm-3"/>
                        </div>
                    </div>

                    <div className="container">
                        <div className="row">
                            <div className="col-sm-12"><br/>

                                <table className="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>CIOC</th>
                                            <th>Country</th>
                                            <th>Capital</th>
                                            <th>Region</th>
                                            <th>Sub Region</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {this.state.countriesClone.map(country => <RowCreator item={country} key={country.cioc}/>)}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
        )}
}

export default DisplayCountries;

但是当我查看 CoreUI 页面的视图时,我不知道在哪里添加我的构造函数等。任何想法

以下是其中一个页面的 .js 文件示例:

import React, { useState, useEffect } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import {
  CBadge,
  CCard,
  CCardBody,
  CCardHeader,
  CCol,
  CDataTable,
  CRow,
  CPagination
} from '@coreui/react'

import processesData from './ProcessData'

const getBadge = status => {
  switch (status) {
    case 'Active': return 'success'
    case 'Inactive': return 'secondary'
    case 'Pending': return 'warning'
    case 'Banned': return 'danger'
    default: return 'primary'
  }
}

const Processes = () => {
  const history = useHistory()
  const queryPage = useLocation().search.match(/page=([0-9]+)/, '')
  const currentPage = Number(queryPage && queryPage[1] ? queryPage[1] : 1)
  const [page, setPage] = useState(currentPage)

  const pageChange = newPage => {
    currentPage !== newPage && history.push(`/processes?page=${newPage}`)
  }

  useEffect(() => {
    currentPage !== page && setPage(currentPage)
  }, [currentPage, page])

  return (
    <CRow>
      <CCol xl={12}>
        <CCard>
          <CCardHeader>
            <h4 id="process" className="card-title mb-0">Processes</h4>
          </CCardHeader>
          <CCardBody>
          <CDataTable
            items={processesData}
            fields={[
              { key: 'id', _classes: 'font-weight-bold' },
              'name', 'startDate', 'endDate'
            ]}
            columnFilter
            tableFilter
            hover
            sorter
            striped
            itemsPerPageSelect
            itemsPerPage={5}
            activePage={page}
            clickableRows
            onRowClick={(item) => history.push(`/process/${item.id}`)}
          
          />
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>
  )
}

export default Processes

我认为您感到困惑,因为在 core-ui 页面中,编写了一个使用挂钩的功能组件。要阅读有关钩子的更多信息,如果您还没有阅读官方文档,请阅读。 https://reactjs.org/docs/hooks-intro.html

useState useEffect

您可以将 class 组件转换成这样的功能组件

const DisplayCountries = () => {
  [countries, setCountries] = useState([]);

  useEffect(() => {
    const axios = require("axios");
    const url = "http://localhost:8080/demo/api/countries";
    axios
      .get(url)
      .then((res) => {
        setCountries(res.data);
      })
      .catch((error) => {
        console.error("Error", error);
      });
  }, []); // Empty array of dependency makes it equivalent to componentDidMount

  return (<div/>) // render your element like you'd do in a class component
};