首页 > 解决方案 > 有些屏幕可以从 API 获取,而有些则不能?

问题描述

我在大约十个屏幕上进行了完全相同的 fetch 调用,但当我在 iPhone 上以调试模式运行时,其中只有一半实际上能够访问 API。例如,这不起作用:

  const fetchUser = useCallback(async () => {
    fetch('https://www.somerandomsite.io/api/user_detail', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: props.user,
      })
    })
    .then((response)=> response.json())
    .then((json)=> {
      setShares(json.user.shares);
      setFollowers(json.user.followers.length);
      setFollowing(json.user.following.length);
      setBio(json.user.bio);
      setProfilePhoto(json.user.profile_photo);
      setAuthUser(username == props.user)
      setUserId(json.user._id);
      setPremium(json.user.premium);
      if (authUserId == json.user._id) {
        setAuthUser(true);
      }
      else {
        setAuthUser(false);
      }
    })
    .catch((error)=> {
      console.log(error);
    })
  });

而这样做:

  const fetchShares = useCallback(async () => {
    fetch('https://www.somerandomsite.io/api/feed', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        page: page,
      })
    })
    .then((response)=> response.json())
    .then((json)=> {
      json.shares.reverse();
      for (var i = 0; i < json.shares.length; i++) {
        if (json.shares[i].comments_len < 3) {
          json.shares[i].end = true;
        }
      }
      setShares(json.shares);
      var clone = JSON.parse(JSON.stringify(message));
      json.shares.forEach(share=>{
        clone[share._id] = '';
      });
      setReplyTo(clone);
      setMessage(clone);
    })
    .catch((error)=> {
      console.log(error);
    })
  });

在不起作用的屏幕上,我收到错误“无法连接到 Metro 服务器”。有谁知道发生了什么?

标签: react-native

解决方案


推荐阅读