React Native- Hooks issue

huangapple go评论61阅读模式
英文:

React Native- Hooks issue

问题

// 获取潜在客户
const getLeadnew = useCallback(() => {
//fetch('https://3ed6-122-165-218-218.in.ngrok.io/api/Proaddall', {
fetch(${BASE_URL}/api/leadsappall, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: Bearer ${userInfo.token},
},
})
.then((res) => {
return res.json();
})
.then((res) => {
console.log(res.leads);
setLeadnew(res.leads);
//筛选方法输入
//console.log(Leadnew);
})
.catch((e) => {
console.log(e);
});
},);

#如何修复多次重新渲染
可以使用 flatlist 来查看和应用筛选方法。每次筛选方法都可以多次重新渲染数据,以获得 "无法将 undefined 或 null 转换为对象"。还可以使用相同的方法来获取名称以匹配 id。

英文:
  // Fetch Leads
const getLeadnew = useCallback(() => {
  //fetch('https://3ed6-122-165-218-218.in.ngrok.io/api/Proaddall', {
  fetch(`${BASE_URL}/api/leadsappall`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      Authorization: `Bearer ${userInfo.token}`,
    },
  })
    .then((res) => {
      return res.json();
    })
    .then((res) => {
      console.log(res.leads);
      setLeadnew(res.leads);
      //Filter Method input
      //console.log(Leadnew);
    })
    .catch((e) => {
      console.log(e);
    });
},);

#How to fix multiple re-renders
This can be using the flatlist to view and apply the filter method. Each filter method the data can be re-render the multiple times to get the "cannot convert undefined or null to object". And also using same method to get name to match the id.

答案1

得分: 0

如果你想要使用 useEffect 钩子来调用一些 API 并且只想渲染一次,你可以尝试将依赖数组添加为空数组,类似于以下方式:

React.useEffect(() => {
   myApiFunction().then(_ => console.log('myApiFunction'));
}, []);

myApiFunction 将是包含用于获取 API 数据的代码以及一些 try-catch 来处理错误的函数。

希望这对你有帮助,加油!

英文:

Could you show some example of the code for future question.

If you want to use the useEffect hook to call some api and want only render once you could try add the dependency array to and empty array something like this:

React.useEffect(() => {
   myApiFunction().then(_ => console.log('myApiFunction'));
  }, []);

myApiFunction will be the function that have your code to fetch the api with some try catch to handle errors.

I hope this help. cheers

huangapple
  • 本文由 发表于 2023年3月31日 17:27:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75896858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定