【发布时间】:2020-10-22 02:01:16
【问题描述】:
我正在尝试在一个函数中执行多项操作。当我提交表单时,我需要它们一个接一个地发生
1. Get back data (here is where the meals array is set)
2. Check the length of the meals array
3. Append a slide if the length of the array is longer than 1
4. Slide to that new slide if meals length is indeed greater than 1
我正在尝试回调和异步函数,但它仍然无法正常工作。提交表单时,会设置餐点数组。然后,如果我再次提交,则检查餐长度数组,如果 if/else 语句为真,则附加幻灯片。
请帮帮我!我会采取任何可行的解决方案 - 承诺、回调等。
这是第一个函数的代码:
const handleSearch = (e) => {
e.preventDefault();
if (searchVal.trim() !== '') {
let foodSearch = searchVal.trim().replace(/ /g, '+')
databaseFetch(`${BASE_URL}search.php?s=${foodSearch}`)
secondFunction()
} else {
setSearchVal('')
}
}
这是第二个功能:
function secondFunction() {
if (meals.length > 1) {
slide1Horizontal.appendSlide(`<div class="swiper-slide">${ReactDOMServer.renderToString(<SearchResults />)}</div>`)
slide1Horizontal.slideTo(2, 1000)
}
这里是原始的 fetch 函数:
const databaseFetch = async foodToSearch => {
setLoading(true)
let returned = await (await fetch(foodToSearch));
if (returned.ok) {
let result = await returned.json()
//console.log(result)
setMeals(
result.meals !== null
? [...result.meals]
: []
)
//console.log(meals)
} else {
setError({
error: true,
statusCode: returned.status,
statusText: returned.statusText
})
}
setLoading(false)
}
}
【问题讨论】:
-
什么是
setMeals,meals变量的作用域是什么? -
我正在使用 React Hooks
标签: javascript reactjs asynchronous promise react-hooks