How do I maintain a central/global object for some data with react-router?
Let's say my React site has 20 different routes. 15 out of those 20 routes need one JSON file from the server that almost never changes. I hate having to GET "/api/mydata" for every new URL/route.
I guess I can save the data in React's context , but that seems hacky and may not even work. Is there a more elegant solution for sharing data between react-router components?
Edit: I partially solved this by creating a Data.js file:
export var myData = function(cb) {
ajax('GET', '/api/mydata', resp => {
myData = function() {
return cb(resp);
};
cb(resp);
});
};
and use it like this:
myData(data => data.map(/* ...use the data */));
That way the data is guaranteed to only be fetched once per lifecycle.
Arrr... if you don't want to use redux or flux, you can create a singleton like this in a new js file
let appState = {};
export default appState;
First do ajax to fill the data into this singleton. Then import it to everywhere you want the data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.