gpt4 book ai didi

javascript - React hooks 重置状态并获取数据

转载 作者:行者123 更新时间:2023-12-02 21:30:10 25 4
gpt4 key购买 nike

我正在使用 React Native 构建一个应用程序。我正在使用 FlatListonRefresh 处理程序:

 <FlatList 
data={data}
renderItem={renderPost}
keyExtractor={(item, index) => index.toString()}
onEndReached={handleLoadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={renderFooter}
refreshing={isRefreshing}
onRefresh={handleRefresh}>
</FlatList>

在该 onRefresh 处理程序中,我重置数据列表并获取新数据:

 const handleRefresh = () => {
setData([]);
setIsRefreshing(true);
fetchData();
}

问题是 data 从未设置为 []。我可以在这里读到这是预期的行为: useState set method not reflecting change immediately

但是什么是更好的方法呢?因为当我使用 useEffect 时,我遇到了同样的问题:

useEffect(() => {
setData([])
fetchData();
}, [isRefreshing]);

const handleRefresh = () => {
setIsRefreshing(true);
}

isRefreshing 永远不会设置为 true

解决这个问题的最佳方法是什么?

--编辑

fethData 方法:

const fetchData = () => {
const url = 'my-api-url.com?page=' + page;

fetch(url, {
method: 'GET',
}).then((response) => response.json())
.then((json) => {
setData(data.concat(json.data));
setIsLoading(false);
setIsRefreshing(false);
});
}

最佳答案

如果您明白我在这里想做的事情,它可能最适合您

// how about isolating all the data fetch related hooks
// fetch will be called anytime your request params updates
// qs is from query string library

const useDataFetch = (url, method, params) => {
const [refreshing, setRefreshing] = useState(false)
const [fetching, setFetching] = useState(false)
const [data, setData] = useState([])

useEffect(() => {
async (() => {
const url = `${url}?${qs.stringify(params)}`

// we set fetching to true while data is still to be fetched
await setFetching(true)
const rawResponse = await fetch(url, {method})

// and set it back to false when done
const newData = rawResponse.json().data

if (refreshing) {
setData(newData)
setRefreshing(false)
} else {
setData([...data, ...newData])
}

setFetching(false)
})()
}, [params])

return {refreshing, setRefreshing, fetching, data}
}

// and use it like this
// only params is outside of useDataFetch because of the feature refreshing
export default myApp = () => {
const [params, setParams] = useState({page: 1})
const {refreshing, setRefreshing, fetching, data} = useDataFetch('my-api-url.com', 'GET', params)

const handleRefresh = async () => {
await setRefreshing(true)
setParams({page: 1})
}

return (
<FlatList
data={data}
renderItem={renderPost}
keyExtractor={(item, index) => index.toString()}
onEndReached={handleLoadMore}
onEndReachedThreshold={0.5}
ListFooterComponent={renderFooter}
refreshing={refreshing}
onRefresh={handleRefresh}>
</FlatList>
)
}

// now things are reuseable and less code from now on

关于javascript - React hooks 重置状态并获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60639272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com