Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

reactjs - Map is not a function within React return

Hi i stumbled on this strange situation.

So in the code example i indicated in comments where the problem is situated.

Within useEffect i get back the right data, an array of objects. When i want to use the data within the return, i get the following errors:

  1. shopFiltered.map is not a function

  2. Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Thing that's quite odd though is that the log of shopFiltered in useEffect logs 3 times in the console: the first time it logs an array of objects, the second time it logs 1 (int) en the third time it logs 2 (int). What could be the explanation of this?

Thanks in advance

 export default () => {
 const [shopFiltered, setShopFiltered] = useState([]);

 useEffect(() => {
    axios
      .get("My url which returns the data")
      .then((resp) => {
        resp.data.forEach((shop) => {
          Geocode.fromAddress(shop.acf.address).then(
            (response) => {
              let dis = getDistance(
                {
                  latitude: parseFloat(
                    response.results[0].geometry.location.lat
                  ),
                  longitude: parseFloat(
                    response.results[0].geometry.location.lng
                  ),
                },
                {
                  latitude: parseFloat(userCoords.lat),
                  longitude: parseFloat(userCoords.lng),
                }
              );
              if (dis / 1000 > 10) {
                setShopFiltered(shopFiltered.push(shop));
              }
            },
            (error) => {
              console.error(error);
            }
          );
        });
      });
  }, []);

  useEffect(() => {
    console.log(shopFiltered); // This gives me an array of objects, which is fine
  }, [shopFiltered]);



return (
    <React.Fragment>
        {!!shopFiltered && shopFiltered.map((data) => {
          console.log(data); // When i want to use the array and map over it here, i get the errors
        })}
    </React.Fragment>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The shopFiltered.push(shop) doesn't return the array. it returns the pushed item itself. so setShopFiltered(shopFiltered.push(shop)) is not setting an array.

change that to setShopFiltered(shopFiltered.concat(shop))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...