首页 > 解决方案 > React native:fetch 在每次刷新时都会重复数据

问题描述

我有一个反应原生应用程序,我在其中从这样的 api 获取数据

export const treatmentsList = (props) => {
const [treatments, setTreatments] = useState([]);
const healthcareUrl = // an url ..


async function getAllTreatmentsByPathwayId(id) {
  const url = healtcareUrl + '/api/v1/treatments/by-pathway/' + id;
  var token;
  await AsyncStorage.getItem('access_token').then((res) => {
    token = res;
  });
  return fetch(url, {
    method: 'GET',
    headers: {  Authorization: 'Bearer ' + token },
  })
    .then((response) => response.json())
    .catch((error) => console.error(error));
}


  const getTreatmentOfPathway = async () => {
    await getAllTreatmentsByPathwayId(8).then((res) => {
      res.map((products) => {
        setTreatments((treatments) => [
          ...treatments,
          {
            id: products.id,
            isEffectuated: products.isEffectuated,
            name: products.treatmentType.name,
            description: products.treatmentType.description,
            image: products.treatmentType.image,
          },
        ]);
      });
    });
    return treatments;
  };

  useEffect(() => {
    getTreatmentOfPathway();
  }, []);

return (
<View>
{treatments.map(function (theItem, i) {return (
<View>
<Text>
{theItem.name}
<Text>
<View>)})}
</View>
);
}

提取工作正常,我得到了我的两个治疗名称(在我的情况下,两个治疗名称是椎板切除术和假体)但是每次我在 Visual Studio Code 中进行更改然后按 ctrl+s 保存时,应用程序都会刷新复制这些两个名字。例如,在第一个渲染中,它 在第二次刷新后显示 椎板切除假体 它在第三次刷新后显示椎板切除术假体椎板切除术它显示 椎板切除术假体椎板切除术假体椎板切除术 我的意思是为什么在每次刷新时它不会自动设置治疗([])喜欢它在上述代码的第二行声明?我找到的唯一解决方案是setTreatments([])getTreatmentOfPathway() 这样添加

const getTreatmentOfPathway = async () => {
setTreatments([]); // setting the treatments empty 
    await getAllTreatmentsByPathwayId(8).then((res) => {
      res.map((products) => {
        setTreatments((treatments) => [
          ...treatments,
          {
            id: products.id,
            isEffectuated: products.isEffectuated,
            name: products.treatmentType.name,
            description: products.treatmentType.description,
            
            image: products.treatmentType.image,
          },
        ]);
      });
    });
    return treatments;
  };

有人有解释和解决方案吗?

标签: javascriptreactjsreact-nativeapirest

解决方案


好的。我理解你的问题。

setTreatments((treatments) => [
      ...treatments,
      {
        id: products.id,
        isEffectuated: products.isEffectuated,
        name: products.treatmentType.name,
        description: products.treatmentType.description,
        
        image: products.treatmentType.image,
      },
    ]);

每次此代码执行数组时,只添加数组中的更多元素。保留... operator数组数据并添加更多项目。

您需要创建一个临时数组并在迭代结束后添加产品,然后设置您的状态。像这样。

    let temparray = []
    res.map((products) => {
          temparray.push({
                id: products.id,
                isEffectuated: products.isEffectuated,
                name: products.treatmentType.name,
                description: products.treatmentType.description,
                image: products.treatmentType.image,
              }}
          });

setTreatments(temparray)

推荐阅读