【问题标题】:Making GET request within JSX.element function react native在 JSX.element 函数中进行 GET 请求反应原生
【发布时间】:2021-06-27 05:53:26
【问题描述】:

我目前正在开发一个 expo 和 react-native 应用程序,我正在尝试获取一些带有纬度和经度的 JSON,并将其显示为地图标记。

我知道以下内容有很多错误,但我很难找到任何用于创建 GET 请求和修改 JSX.element 函数内部信息的文档。除此之外,我也不确定如何每隔几分钟重复获取以不断更新此组件状态

如果这是基本的,我很抱歉,我对原生反应很陌生,这些 JSX.element 函数不是类是令人困惑的。

export const Map = (): JSX.Element => (
  state = {
    responseData: []
  }
  fetch('https://apiURL', {method: 'GET'})
  .then((response) => response.json())
  .then((responseJson) => {
    this.setState({responseJson})
    console.log(responseJson)
  })
  .catch((error) => {
    console.error(error);
  });
    <MapView
        style={styles.map}
        loadingEnabled={true}
        region={{
            latitude: 37.956290,
            longitude: -91.779460,
            latitudeDelta: 0.015,
            longitudeDelta: 0.0121
        }}
    >
      <MapView.Marker
        coordinate={{
          latitude: responseData.latitude,
          longitude: responseData.longitude
        }}
        title={"Location"}
        description={"Location of Location"}
      />
    </MapView>
);

我在另一个 JSX.element 组件中使用这个 Map 组件:

export const MapScreen = (): JSX.Element => (
    <SafeAreaView forceInset={{top: 'always'}}>
      <Map/>
    </SafeAreaView>
);

【问题讨论】:

  • 基于函数的组件(我认为你的意思是“JSX.element 函数”)没有this.useState。您需要使用 hooks,例如阅读reactjs.org/docs/hooks-effect.html.
  • 所以我可以将 JSX 元素粘贴在 return 语句中,并且该函数应该可以正常工作?
  • 不,这既不是我所说的,也不是文档显示的。您确实需要返回元素,但这不足以修复您发布的内容。您还应该阅读基本的箭头函数语法,第二个很好,但第一个坏了。

标签: javascript reactjs react-native expo


【解决方案1】:

原来我必须从函数中删除 JSX.Element 语句,并从另一个函数中获取数据。

const useFetch = url => {
  const [data, setData] = useState(null);

  async function fetchData(){
    const response = await(fetch(url))
    const json = await response.json();
    setData(json);
  }

  useEffect(() => {
    fetchData()

    const interval=setInterval(() => {
      fetchData()
    }, 6000)

    return()=>clearInterval(interval)
  },[url]);

  return data
};
export const Map = () => {
  const data = useFetch('APIURL')

  if(!data){
    return <Text>Loading...</Text>
  }

  else {
  return(
    <MapView
      style={styles.map}
      loadingEnabled={true}
      region={{
          latitude: 37.956290,
          longitude: -91.779460,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121
      }}
    >
      <MapView.Marker
        coordinate={{
          latitude: data.latitude,
          longitude: data.longitude
        }}
        title={"title"}
        description={"desc"}
      />
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 2023-03-20
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多