我试图从我的API中获取数据,并将其存储到使用setState钩子在一个变量中的react变量中。我的代码在这里
import { useState, useEffect } from 'react';
import axios from 'axios'
const rest_base = wpbpressdata.rest_url
const api = rest_base + '/services'
const ServicesCategory = () => {
const [services, setServices] = useState(null)
useEffect( () => {
axios.get( api )
.then( (res) =>{
setServices(res.data)
})
}, [] )
return(
services === null ? 'loading' : services.map = (data) => {
<h3>{data.service_name}</h3>
}
)
}
export default ServicesCategory
但是我得到这个错误Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
{
services === null ? 'Loading' : services.map(p => <h3>{p.service_name}</h3>)
}
调用map
函数不赋值
如果你的services
是null返回'loading'这是一个字符串,不是JSX
import { useState, useEffect } from 'react';
import axios from 'axios'
const rest_base = wpbpressdata.rest_url
const api = rest_base + '/services'
const ServicesCategory = () => {
const [services, setServices] = useState(null)
useEffect( () => {
axios.get( api )
.then( (res) =>{
setServices(res.data)
})
}, [] )
return(
<>{
!services ?<h1> 'loading'</h1> : services.map(data) => {
<h3>{data.service_name}</h3>
}}</>
)
}
export default ServicesCategory
import React, { useState, useEffect } from 'react';
import axios from 'axios'
const rest_base = wpbpressdata.rest_url
const api = rest_base + '/services'
const ServicesCategory:React.FC<any> = () => {
const [services, setServices] = useState(null)
const fetchServices=async ()=>{
const response=await axios.get( api )
if(response){
setServices(response.data)
}
}
useEffect( () => {
fetchServices()
}, [] )
if(!services){
return (<p>Loading...</p>);
}
return(
services.map = (data, index) =>
<h3 key={`service${index}`}>{data.service_name}</h3>
)
}
export default ServicesCategory