简体   繁体   English

React js function 未被调用

[英]React js function not being called

In react js, I am fetching data from multiple API and I need to fetch them one by one and also call some functions one by one so I used react state with if statements to make them work.在 react js 中,我从多个 API 获取数据,我需要一个一个地获取它们,并且还一个一个地调用一些函数,所以我使用 react state 和 if 语句来使它们工作。 I am changing the state of different useState variables once one fetch or a particular function is done but even when the state is changed the functions are not running.一旦一次获取或特定的 function 完成,我将更改不同useState变量的 state,但即使更改了 state,功能也不会运行。 The whole code is inside another function but I have not provided it.整个代码在另一个 function 中,但我没有提供。 In the fetchData function, I want to run the functions and fetches synchronously but they are not runningfetchData function 中,我想运行函数并同步获取,但它们没有运行

let [origData, setOrigData] = useState(null);
let [imageId, setImageId] = useState([]);
let [myItems, setMyItems] = useState([]);
let [finalData, setFinalData] = useState([]);
let [getData, setGetData] = useState(false);
let [itemId, setItemId] = useState(false);

let fetchData = () => {
  fetch('http://127.0.0.1:8000/api/get-order-item/' + sessionStorage.getItem('id'), {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer' + ' ' + sessionStorage.getItem('token'),
    },
  })
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      if (data) {
        setMyItems(data);
        setGetData(true);
      }
    });

  if (getData === true) {
    myItems.map((e) => {
      console.log(e);
    });
    setItemId(true);
  }

  if (itemId === true) {
    fetch('http://127.0.0.1:8000/api/data')
      .then((response) => {
        return response.json();
      })
      .then((info) => {
        setOrigData(info);
        console.log('fetch done');
      });
  }
};

React is not meant to run synchronously. React 并不意味着同步运行。 The view rendering has priority and shouldn't be blocked by some code which is not view-relevant in the first place.视图渲染具有优先权,不应被某些与视图无关的代码阻塞。 The concept for running view-blocking code is useEffect .运行视图阻塞代码的概念是useEffect You get the idea of using APIs on theexplanation of useEffect你在useEffect 的解释中得到了使用 APIs 的想法

The reason this doesn't work is it relies on state data being set in the function block.这不起作用的原因是它依赖于在 function 块中设置的 state 数据。 There is no reason why you need this state to send the second request when you have the data from the first response to hand!当您手头有第一个响应的数据时,没有理由需要这个 state 来发送第二个请求!

Also, response.json() is a promise and must be resolved!另外, response.json()是一个 promise,必须解决!

I've refactored your code so it is easier to follow using async/await.我已经重构了您的代码,因此使用 async/await 更容易理解。

const fetchData = async() => {
    const response = await fetch('http://127.0.0.1:8000/api/get-order-item/' + sessionStorage.getItem('id'), {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer' + ' ' + sessionStorage.getItem('token')
        }
    })
    const data = await response.json();
    
    if(data) {
        setMyItems(data)
        /// setGetData(true) <- dont need
        data.forEach(
            (e) => {
                console.log(e) // <- why are you logging every item?
            }
        )

        const infoResponse = await fetch('http://127.0.0.1:8000/api/data')
        const infoData = await infoResponse.json();

        setOrigData(infoData)
        console.log('fetch done')

    }
}

useEffect(() => {
    (async() => {
        await fetchData()
    })()
}, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM