简体   繁体   English

使用react-router的全局数据

[英]Global data with react-router

How do I maintain a central/global object for some data with react-router? 如何使用react-router维护某些数据的中心/全局对象?

Let's say my React site has 20 different routes. 假设我的React网站有20条不同的路线。 15 out of those 20 routes need one JSON file from the server that almost never changes. 这20条路线中的15条需要一个来自服务器的JSON文件,几乎不会发生变化。 I hate having to GET "/api/mydata" for every new URL/route. 我讨厌为每个新的URL /路由获取“/ api / mydata”。

I guess I can save the data in React's context , but that seems hacky and may not even work. 我想我可以在React的上下文中保存数据,但这看起来很糟糕,甚至可能无法正常工作。 Is there a more elegant solution for sharing data between react-router components? 在react-router组件之间共享数据是否有更优雅的解决方案?

Edit: I partially solved this by creating a Data.js file: 编辑:我通过创建Data.js文件部分解决了这个问题:

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 Arrr ...如果你不想使用redux或flux,你可以在一个新的js文件中创建这样的单例

let appState = {};
export default appState;

First do ajax to fill the data into this singleton. 首先做ajax将数据填充到这个单例中。 Then import it to everywhere you want the data. 然后将其导入到您想要数据的任何位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM