简体   繁体   English

在本机反应中映射 state 数组

[英]Mapping state array in react native

I'm not sure what's going wrong.我不确定出了什么问题。 I am importing a function that uses useState and useEffect.我正在导入一个使用 useState 和 useEffect 的 function。 the function returns the variable in my state with data from a fetch call. function 返回我的 state 中的变量以及来自 fetch 调用的数据。 However, when I try to map over that data, I get an error: map is not defined.但是,当我尝试对这些数据进行 map 时,我收到一个错误:map 未定义。 My syntax looks right and this works in regular react, so I'm not sure what's going wrong now.我的语法看起来正确,这在常规反应中有效,所以我不确定现在出了什么问题。 I am getting a response back, the file is being imported/exported correctly and the state is updating (the APIKey used is hidden for this post) and pointers would be great!我收到了回复,文件正在正确导入/导出,并且 state 正在更新(此帖子使用的 APIKey 是隐藏的)并且指针会很棒!

code for data and updating state:数据和更新代码 state:

export function grabLocationData() {
  const [data, updateData] = useState([]);
  console.log("Data!", data);
  const [location, updateLocation] = useState("");
  useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log("lat", position.coords.latitude);
        console.log("lng", position.coords.longitude);
        const { latitude, longitude } = position.coords;
        updateLocation(`${latitude},${longitude}`);
      },
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
    const url = `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${query}&location=${location}&radius=10000&key=${apiKey}`;
    console.log("console log!!!", url);
    fetch(url)
      .then((response, err) => {
        if (err) throw err;
        return response.json();
      })
      .then((responseJson) => {
        updateData(responseJson);
      });
  }, []);
  return data;
}

code for mapping映射代码

export default Locations = (props) => {
  const apiKey = "AIzaSyD3o3hDRwSZTVhlUIDOjGQ1ZqevG6fnWII";
  const data = grabLocationData();
  console.log(data);
  return (
    <ScrollView>
      {data.results.map((bank) => {
        return <View>{bank.name}</View>;
      })}
    </ScrollView>
  );
};

As @Will said in the comment, you can try to split your code into two differents effects.正如@Will 在评论中所说,您可以尝试将代码拆分为两种不同的效果。 You will use the location state as deps for the second effect to be triggered.您将使用位置 state 作为触发第二个效果的部门。

export function grabLocationData() {
  const [data, updateData] = useState([]);
  const [location, updateLocation] = useState('');
  const [url, setUrl] = setState(
    `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${query}&location=${location}&radius=10000&key=${apiKey}`
  );

  // Effect triggered after the location changes
  useEffect(() => {
    // Prevent the effect to be triggered on initial render, only location's update
    if (location !== []) {
      fetch(url)
        .then((response, err) => {
          if (err) throw err;
          return response.json();
        })
        .then((responseJson) => {
          updateData(responseJson);
        });
    }
  }, [location]);

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        updateLocation(`${latitude},${longitude}`);
      },
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
  });

  return data;
}

I added the url as a state but since i don't know where the variables query and apiKey come from, feel free to do whatever you want with this.我将 url 添加为 state 但由于我不知道变量queryapiKey的来源,因此请随意使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM