Reactjs CoreUI进行API调用

Reactjs CoreUI进行API调用,reactjs,core-ui,Reactjs,Core Ui,我已经创建了一些基本的初学者应用程序。但现在我想尝试使用一个模板“核心ui” 我想向一些外部端点发出请求并检索一些数据,但我不确定在哪里执行 以下是我自己做的: import React from 'react'; import RowCreator from './RowCreator'; class DisplayCountries extends React.Component { constructor(props){ super(props);

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

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

以下是我自己做的:

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;
从“React”导入React;
从“/RowCreator”导入RowCreator;
类DisplayCountries扩展了React.Component{
建造师(道具){
超级(道具);
this.state={countries:[],
countriesClone:[]
};
}
componentDidMount(){
const axios=require('axios');
常量url=http://localhost:8080/demo/api/countries';
get(url)。然后(res=>{
console.log(res.data);
这个.setState({国家:资源数据,
countriesClone:res.data});
}).catch(错误=>{
console.error('error',error);
})
}
更改(事件){
var filteredString=event.target.value;
var filteredCountries=[];
for(本州的var国家/地区){
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.subsection.toLowerCase().indexOf(filteredString.toLowerCase())>=0){
过滤国家/地区。推送(国家/地区);
}
}
this.setState({countriesClone:filteredCountries});
}
render(){
返回(
搜索国家
用于筛选国家/地区列表的演示



CIOC 国家 首都 区域 次区域 {this.state.countriesClone.map(country=>)} )} } 出口违约国家;
但是当我查看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
import React,{useState,useffect}来自“React”
从“react router dom”导入{useHistory,useLocation}
进口{
CBadge,
CCard,
CCardBody,
CCardHeader,
CCol,
CDATA表格,
乌鸦,
假牙
}来自“@coreui/react”
从“/ProcessData”导入ProcessData
const getBadge=状态=>{
开关(状态){
案例“活动”:返回“成功”
案例“非活动”:返回“次要”
案例“挂起”:返回“警告”
案例“禁止”:返回“危险”
默认值:返回“主”
}
}
常量进程=()=>{
const history=useHistory()
const queryPage=useLocation().search.match(/page=([0-9]+)/,“”)
const currentPage=Number(查询页面和查询页面[1]?查询页面[1]:1)
const[page,setPage]=useState(当前页面)
const pageChange=newPage=>{
currentPage!==newPage&&history.push(`/processs?page=${newPage}`)
}
useffect(()=>{
当前页面!==页面和设置页面(当前页面)
},[currentPage,page])
返回(
过程
history.push(`/process/${item.id}`)}
/>
)
}
导出默认进程

我想您会感到困惑,因为在
核心ui
页面中,编写了一个使用挂钩的功能组件。要了解更多关于钩子的信息,请浏览官方文档(如果您没有)

您可以像这样将类组件转换为功能组件

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
};
constdisplaycountries=()=>{
[countries,setCountries]=useState([]);
useffect(()=>{
常量axios=要求(“axios”);
常量url=”http://localhost:8080/demo/api/countries";
axios
.get(url)
。然后((res)=>{
setCountries(res.data);
})
.catch((错误)=>{
控制台错误(“错误”,错误);
});
},[]);//依赖项的空数组使其等效于componentDidMount
return()//像在类组件中一样呈现元素
};