问题
What currently are React Native's default behaviors for caching in fetch
calls? The official FB guides simply say "look at Mozilla!" but we're not on a web browser. I would assume cache behavior is custom here as result of the middleware.
Let's say I do: fetch("https://exampleserver.com/myfile.json")
Are requests automatically cached once called?
Is the request contents of
myfile.json
cached the entire "session" (ie: App is running active/bg, but not forced closed by user).- Where is the request cached? Ie: is it using
AsyncStorage
- Would
fetch
the URL again result in the app reading cache. - How "fast" is caching, if for some reason I have to instantly request
myfile.json
multiple times, is it going to basically ignore cache at that point and make all those separate calls? (I am seeing this behavior in debugger)
- Where is the request cached? Ie: is it using
When I force close the app, and reopen, does this cache still exist?
- If so, can I request the cache to persist?
Any of this behavior different in iOS than Android?
Does Expo affect this at all?
Knowing at least some of this would help decide whether I need to write custom caching situation with AsyncStorage like so https://gist.github.com/dslounge/18e555250a8df1f8218d702b21910eeb
回答1:
React Native’s fetch
API bridges to NSURLSession
on iOS and okhttp3
on Android. Both of these libraries strictly follow the HTTP caching spec. The caching behavior will depend primarily on the Cache-Control
and Expires
headers in the HTTP response. Each of these libraries have their own configuration you can adjust, for example to control the cache size or to disable caching.
The cached files are not guaranteed to persist until they expire. The system can purge them whenever it wants.
If you make three requests really fast then you will, in general, succeed, because the caching is neither immediate nor guaranteed.
In general: set your HTTP response headers appropriately, but don’t rely on HTTP caching to behave a certain way for the proper functioning of your app. If you want a guarantee that a second request won’t actually make a network connection, you need to write that yourself.
I don’t think Expo affects this.
来源:https://stackoverflow.com/questions/51904696/what-are-react-natives-caching-behaviors-for-fetch