如何将初始数据从 rails 加载到 redux [英] How to load initial data from rails to redux

查看:51
本文介绍了如何将初始数据从 rails 加载到 redux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to load json from rails, and pass it to redux createStore.

let initialStore = window.INITIAL;

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

但我总是未定义,或者在存储后只是 window.INITIAL 返回值.

But i always get undefined, or just window.INITIAL return value after store.

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

At first, store loads with empty object, then fetch action is dispatched, and i get updated store with json, but i already got error, when i'm trying to call something like { product.title } on empty object. No matter what I do, i can't load json before redux stuff begins, even with global data, like this.

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

API 和控制器很简单.

Api and controller is simple.

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

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

How do you handle this? I want to do it without any gems like react-rails etc, i can't pass all initial state to Root component in one place.

推荐答案

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

In the question above you have the following:

let initialStore = window.INITIAL;

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

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

The problem with the above code is that it will only populate your store with window.INITIAL as it exists when the page first loads. Any further changes to window.INITIAL will be ignored.

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

What you need to do is populate window.INITIAL with your initial data in your server rendered code. That is, simply place the script block before your redux code:

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

就是这样.现在摆脱 AJAX 调用.你不需要它.这也会提高很多性能.与强迫用户在页面已经呈现之后等待额外的请求不同,用户在获取页面其余部分的同时获取所有数据.

That's it. Now get rid of the AJAX call. You don't need it. This will be a lot more performant too. Instead of forcing the user to wait on an additional request after the page has already rendered, the user instead gets all the data at the same time as the rest of the page.

这篇关于如何将初始数据从 rails 加载到 redux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆