首页 文章

如何将rails中的初始数据加载到redux

提问于
浏览
3

我试图从rails加载json,并将其传递给redux createStore .

let initialStore = window.INITIAL;

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(rootReducer, initialStore);

但我总是得到未定义,或只是window.INITIAL后存储的返回值 .

首先,使用空对象存储加载,然后调度fetch操作,并使用json更新存储,但是当我尝试在空对象上调用之类的东西时,我已经收到错误 . 无论我做什么,我都无法在redux开始之前加载json,即使是像这样的全局数据 .

(function() {
  $.getJSON('http://localhost:3000/products.json', function(data) {
    return window.INITIAL = data;
  });
});

Api和控制器很简单 .

def index
  products = Product.all
  render json: products
end

你怎么处理这个?我想在没有像react-rails等任何宝石的情况下这样做,我无法在一个地方将所有初始状态传递给Root组件 .

1 回答

  • 4

    在上面的问题中,您有以下内容:

    let initialStore = window.INITIAL;
    
    const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
    const store = createStoreWithMiddleware(rootReducer, initialStore);
    

    上述代码的问题在于,它只会在页面首次加载时使用 window.INITIAL 填充您的商店 . 对 window.INITIAL 的任何进一步更改都将被忽略 .

    您需要做的是使用服务器呈现代码中的初始数据填充 window.INITIAL . 也就是说,只需将脚本块放在redux代码之前:

    <script>
        var INITIAL = { /* this object should match the shape of your reducer state */ }; 
    </script>
    

    那个's it. Now get rid of the AJAX call. You don'需要它 . 这也将更高效 . 用户不是在页面已经呈现之后强制用户等待其他请求,而是在与页面的其余部分同时获取所有数据 .

相关问题