如何将这个基于类的Axios请求集成到另一个从Json文件获取数据的基于钩子的代码中?基本上我想用 Axios get 请求替换数据源位置。谢谢。
componentDidMount () {
axios.get('http://192.168.2.94:3000/list-places').then(res => {
this.setState({
posts: res.data
})
})
}
import { LOCATIONS } from '../data/data'
const HomeScreen = props => {
const renderGridItem = itemData => {
return (
<CategoryGridTile
image={itemData.item.image}
title={itemData.item.title}
onSelect={() => {
props.navigation.navigate({
routeName: 'Categories',
params: {
locationId: itemData.item.id
}
})
}}
/>
)
}
return (
<FlatList
keyExtractor={(item, index) => item.id}
data={LOCATIONS}
renderItem={renderGridItem}
/>
)
}
您只想从 API 获取位置数据?这样的东西应该可以工作(代码未经测试(
const HomeScreen = props => {
const [locations, setLocations] = useState(undefined);
useEffect(() => {
async function getLocations() {
const { data } = await axios.get('http://192.168.2.94:3000/list-places');
setLocations(data);
}
getLocations();
}, []);
// ...
return (
<>
{locations && (
<FlatList
keyExtractor={(item, index) => item.id}
data={locations}
renderItem={renderGridItem}
/>
)}
</>
);
};