[英]My program is 'skipping' a fetch request, React.js
它真的很奇怪。
我做的第一次提取工作正常,但是在我的 handleSubmit() 方法中進行第二次提取時,它有點“跳過”它。 它繼續,從不進入 .then 語句,不打印錯誤。 我已經嘗試過其他 API,但老實說它應該可以正常工作,因為第一次幾乎相同並且可以正常工作。 我也試過用 return 語句重寫......
export default function FormContainer() {
const [api, setApi] = useState()
const [showText, setShowText] = useState(false)
const [apiUrl, setApiUrl] = useState('')
const [text, setText] = useState('')
const [display, setDisplay] = useState('')
const [page, setPage] = useState('')
useEffect(() => {
fetch('https://swapi.co/api/') //FIRST TRY, works
.then(response => response.json())
.then(response => setApi(response))
},[])
function handleRadio(event){
setShowText(true)
setPage(event.target.id)
setApiUrl(api[event.target.id])
}
function handleText(event){
setText(event.target.value)
}
function handleSubmit(event){
event.preventDefault();
let list = {};
let found = false;
console.log(apiUrl); //Prints
fetch(apiUrl) //SECOND TRY, fails
.then(response =>{
console.log(response); //Never prints
return response.json();
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error); //Doesnt run
})
while(!found){
list.results.map(item => {
if(item.name.toUpperCase() === text.toUpperCase()){
found = true
let toDisplay = ''
if(page === 'people'){
console.log(page)
}else if(page === 'planets'){
console.log(text)
}else if(page === 'films'){
console.log(page)
}else if(page === 'species'){
console.log(page)
}else if(page === 'vehicles'){
console.log(page)
}else{
console.log(page)
//Starships
}
}
})
if(!found){
if(list.next !== null){
fetch(list.next) //DIDNT GET TO TRY THIS
.then(response => response.json())
.then(response => {list = response})
}else{
found = true
setDisplay('Object not found, are you sure you typed it in correctly?')
}
}
}
}
return (
<div >
<FormRadios handleRadio={handleRadio}/>
<br></br>
{showText ? <FormComponent text={text} handleText={handleText} handleSubmit={handleSubmit}/> : null}
<hr></hr>
<FormOutput display={display}/>
</div>
);
}
當然,我歡迎對我的代碼提出任何建議,因為我在 React.js 和使用鈎子方面是全新的。 提前致謝!
看起來成功了,但我剛剛意識到我的問題是什么。 當再次獲取 api 時,我立即跳轉到下一行代碼,但獲取並不像代碼運行那樣即時。 我在獲取后發生了異常(因為我試圖使用來自獲取的信息),因此獲取無法以足夠快的速度完成以正確使用信息,然后異常運行,當然,控制台日志不起作用。 這基本上就是發生的事情,而且也很有趣。 但是感謝所有的幫助,它真的幫助我弄清楚發生了什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.