【发布时间】:2021-01-30 13:01:01
【问题描述】:
在 react native 代码中,例如我有一个 2 状态。
const [data, setData] = useState([]);
const [page, setPage] = useState(0);
调用函数时,即搜索函数
search = async() => {
setData([]);
setPage(0);
console.log("Page: " + page); // This will return 0 because of the setPage(0) above, or can call setPage((state)) to wait until page set to 0
}
如果多次调用上述搜索功能,则页面为0。是预期的。
但如果这段代码继续,
search = async() => {
setData([]);
setPage(0);
console.log("Page: " + page); // This page will be always increment because fetch then setPage+1 above
fetch(url)
.then((response) => response.json())
.then((json) => { setData(data.concat(json.content)); setPage(page+1); })
.catch((error) => console.error(error))
.finally(() => { });
}
日志将是
Page: 1
Page: 2
Page: 3
预期应该始终是 Page: 0
问题是,如何设置页面为0,然后获取url,所以在获取之前的值始终为0。目的很简单,当这个搜索功能触发时,页面必须为0,然后再次获取数据。
【问题讨论】:
标签: react-native state use-state