在基于功能的组件React中实现基于类的系统

时间:2020-05-06 18:11:30

标签: javascript reactjs axios react-functional-component

我是React和JavaScript的新手。我已经实现了一个基于函数的组件,该组件可迭代一组数据并将相关数据打印在页面上。

function useJobs () {
  const [jobs, setJobs] = React.useState([])
  React.useEffect(() => {
    fetch('/api/jobs/list-jobs', { headers: headers })
      .then(r => r.json())
      .then(setJobs)
  }, [])

  return jobs
}

export default function Jobs () {
  const classes = useStyles()
  const jobs = useJobs()
  return (
    <>
  ....
  {jobs.map(job => (
       <>
       <div className={classes.root} key={job.id}>
       <Container className='jobContainer'>
                    <Typography className={classes.TextHeaders}>
                      <Row>
                        <Col style={{ color: 'black' }}>Title: {job.title} </Col>
                      </Row>
                      <br />

                 <Col>Location: //needs to be implemented </Col>

现在是位置部分,我想基于job.location从我的API中获取一些数据,并在页面上显示代表部分,例如:

 state = {
    locationsCountry:[],
    LocationsRegion: [],
  }
componentDidMount () {
 axios.get(`/api/jobs/view-location/${job.location}/`, { headers: headers }).then(
    res => {
       this.setState({
          LocationsCountry: res.data.map(Location => Location.country)
         })
           console.log(this.state.LocationCountry)
       }
   )
axios.get(`/api/jobs/view-location/${job.location}/`, { headers: headers }).then(
    res => {
       this.setState({
          LocationsRegion: res.data.map(Location => Location.region)
         })
           console.log(this.state.LocationRegion)
       }
   )

render() {
return(
<Col>Location: {this.state.LocationsCountry} {this.state.LocationsRegion} </Col> )}

但是很明显,这个系统是基于类的,在基于函数的示例中,我不知道如何实现类似的东西。如何正确实施呢?

0 个答案:

没有答案