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

IT技术 ruby-on-rails reactjs redux
2021-05-13 22:07:58

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

let initialStore = window.INITIAL;

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

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

首先,使用空对象存储加载,然后调度 fetch 操作,并且我使用 json 更新存储,但是当我尝试在空对象上调用 { product.title } 之类的东西时,我已经出错了。无论我做什么,我都无法在 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个回答

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

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>

而已。现在摆脱 AJAX 调用。你不需要它。这也会提高很多性能。用户不是在页面已经呈现强制用户等待其他请求,而是在获取页面其余部分的同时获取所有数据。