【问题标题】:Integrating class based Axios request to the hook based code将基于类的 Axios 请求集成到基于钩子的代码中
【发布时间】:2019-12-06 22:54:16
【问题描述】:

如何将基于此类的 Axios 请求集成到其他基于钩子的代码中,该代码从 Json 文件中获取数据?基本上我想用 Axios 获取请求替换数据源 LOCATIONS。谢谢。

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}
        />
      )
    }

【问题讨论】:

    标签: reactjs react-native axios react-hooks


    【解决方案1】:

    您只想从 API 获取 LOCATIONS 数据?这样的东西应该可以工作(代码未经测试)

    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}
            />
          )}
        </>
      );
     };
    

    【讨论】:

    • 什么意思 {locations && (...)}
    • 在未定义位置对象之前,FlatList 组件不会呈现
    猜你喜欢
    • 2014-09-13
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2019-09-21
    • 2020-09-26
    相关资源
    最近更新 更多