javascript - 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;
};
有人有解释和解决方案吗?
解决方案
好的。我理解你的问题。
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)
推荐阅读
- sql - 内连接或条件
- asp.net-mvc - 如何在 nopcommerce 4.3 中添加附加字段
- discord - 如何让我的机器人检查作者是否有管理员,如果没有,则发送消息?
- python-2.7 - Yaml 转 CSV 格式
- mysql - 1045,拒绝访问 MySQL 数据库(Flask + SQLAlchemy + MySQL)
- reactjs - 如何在第一次渲染和点击时都渲染 useQuery?[ReactJS,graphql]
- python - Tkinter - 如何立即创建小部件?
- java - Java 项目:无法访问资源目录中的属性文件
- java - 我如何验证文本文件中的电子邮件地址(Java)
- python - 如何对目录中的多个文件使用多处理