【问题标题】:TypeError of Meteor.subscribe function on using Meteor' server render in react router v4在反应路由器 v4 中使用 Meteor 的服务器渲染时 Meteor.subscribe 函数的 TypeError
【发布时间】:2017-09-01 08:41:17
【问题描述】:

我正在使用带有 React 路由器 v4 的 Meteor 的服务器渲染包,但我收到了一个 TypeError,Meteor.subscribe 不是一个函数,我无法弄清楚为什么会发生这种情况或到底出了什么问题

这是我在客户端上的代码:

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import {RenderRoutes} from '../imports/api/routes.jsx'
import { onPageLoad } from 'meteor/server-render';
import ReactDOM from 'react-dom';

import {
  Router,
  Route,
  Link,
  Switch
 } from 'react-router-dom'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

const Application = () => (
   <Router history={history}>
      <RenderRoutes/>
   </Router>
);

onPageLoad(()=> {
   ReactDOM.render(<Application/>, document.getElementById('react-root'));
});

在服务器上:

onPageLoad((sink) => {
   const context = {};

   const App = props => (
      <StaticRouter location={props.location} context={context}>
       <RenderRoutes/>
      </StaticRouter>
   );

  sink.renderIntoElementById('app', renderToString(<App location=
   {sink.request.url} />));
  });

我能够使用上述方法让一个非常简单的应用程序正常工作,是订阅和 createcontainer 导致了错误,有没有单独的方法来处理它们?

这是我在客户端上订阅的方式:

export default createContainer(() => {
  const handle1 = Meteor.subscribe('categories');
  const handle2 = Meteor.subscribe('subcategories');
  const handle3 = Meteor.subscribe('products');
  const isReady1 = handle1.ready()
  const isReady2 = handle2.ready()
  const isReady3 = handle3.ready()
  return {
    products: isReady3 ? Products.find({}).fetch() : [],
    categories: isReady1 ? Categories.find({}).fetch() : [],
    subcats: isReady2 ? SubCategories.find({}).fetch(): [],
  };
 }, B2C);

如果你能弄清楚发生了什么或我犯了什么错误,那就太好了 谢谢

【问题讨论】:

    标签: meteor server react-router


    【解决方案1】:

    删除所有订阅并添加自动发布后,它工作正常,但我觉得这不是一个不合适的解决方案,因为我不想到处发布所有数据,所以必须有一个解决方法吧?

    已解决: 我将所有订阅都放在 Meteor.isClient 块中,所以订阅根本不应该在服务器上运行,即使客户端上存在代码并且正在使用它进行服务器渲染,Meteor.isClient 块应该提供可能导致服务器渲染错误的代码

    【讨论】:

      【解决方案2】:

      另一种解决方案是通过添加 Meteor.subscribe 作为返回对象的函数来对服务器端进行猴子修补,该函数返回一个始终返回 true 的 ready 函数:

      服务器端:

      onPageLoad(sink => {
        const context = {};
        // monkey patching subscribe on the server to be ready immediately
        Meteor.subscribe = (topic) => ({ready: () => true});
      
        sink.renderIntoElementById("app", renderToString(
          <StaticRouter location={sink.request.url} context={context}>
            <App />
          </StaticRouter>
        ));
      });
      

      这样您就不需要单独触摸每个组件。

      【讨论】:

        猜你喜欢
        • 2017-11-11
        • 1970-01-01
        • 2019-04-07
        • 2016-02-05
        • 2017-01-22
        • 2023-04-04
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多