【问题标题】:Mapping state array in react native在本机反应中映射状态数组
【发布时间】:2020-08-10 11:33:19
【问题描述】:

我不确定出了什么问题。我正在导入一个使用 useState 和 useEffect 的函数。该函数使用来自 fetch 调用的数据返回处于我状态的变量。但是,当我尝试映射该数据时,出现错误:未定义映射。我的语法看起来正确,这在常规反应中有效,所以我不确定现在出了什么问题。我收到了回复,文件正在正确导入/导出,状态正在更新(此帖子使用的 APIKey 是隐藏的),指针会很棒!

数据和更新状态代码:

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

映射代码

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

【问题讨论】:

  • useState 状态更改是异步的。您正在调用updateLocation。但是当你完成钩子执行时它仍然是空的。因此,当您尝试获取时,url 的位置部分将为空。尝试将代码分成两个效果。一个设置位置的。定义位置后获取 json 数据的第二个。还要记住为你的 useEffect 使用正确的依赖项。 React hooks docs 是刷新的好地方。

标签: javascript reactjs react-native react-hooks array.prototype.map


【解决方案1】:

正如@Will 在评论中所说,您可以尝试将代码拆分为两种不同的效果。您将使用位置状态作为触发第二个效果的依赖项。

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

我将 url 添加为状态,但由于我不知道变量 query 和 apiKey 来自哪里,请随意使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多