电极在页面源中不显示动态数据

时间:2019-02-28 05:17:13

标签: reactjs walmart-electrode

使用电极,我注意到了这种奇怪的行为-

在页面完全加载所有api调用和数据后查看页面源时,我只能查看静态内容,例如超级链接,标题,页脚链接等。

我创建了一个自定义令牌处理程序,该处理程序检查context对象并填充index.html中存在的自定义令牌。 因此,无论何时console.log(context.user.content),仅记录静态数据,例如超链接,标题,页脚链接。

我想这是问题所在,但是我不能确定为什么电极不能识别动态渲染的内容。

Token-Handler.js文件

import Helmet from 'react-helmet';

const emptyTitleRegex = /<title[^>]*><\/title>/;

module.exports = function setup(options) {
  // console.log({ options });
  return {
    INITIALIZE: context => {
      context.user.helmet = Helmet.renderStatic();
    },
    PAGE_TITLE: context => {
      const helmet = context.user.helmet;
      const helmetTitleScript = helmet.title.toString();
      const helmetTitleEmpty = helmetTitleScript.match(emptyTitleRegex);

      return helmetTitleEmpty ? `<title>${options.routeOptions.pageTitle}</title>` : helmetTitleScript;
    },
    REACT_HELMET_SCRIPTS: context => {
      const scriptsFromHelmet = ["link", "style", "script", "noscript"]
        .map(tagName => context.user.helmet[tagName].toString())
        .join("");
      return `<!--scripts from helmet-->${scriptsFromHelmet}`;
    },
    META_TAGS: context => {
      console.log(context,'123') //this is where I am checking
      return context.user.helmet.meta.toString();
    }
  };
};

default.js

module.exports = {
  port: portFromEnv() || "3000",
  webapp: {
    module: "electrode-react-webapp/lib/express",
    options: {
      prodBundleBase: '/buy-used-car/js/',
      insertTokenIds: false,
      htmlFile: "./{{env.APP_SRC_DIR}}/client/index.html",
      paths: {
        "*": {
          content: {
            module: "./{{env.APP_SRC_DIR}}/server/views/index-view"
          },
        }
      },
      serverSideRendering: true,
      tokenHandler: "./{{env.APP_SRC_DIR}}/server/token-handler"
    }
  }
};

有任何线索吗?

编辑1

但是,呈现在meta标签上的以下任何更新。我不确定这是电极允许的功能还是react-helmet的功能。

编辑2

电极中启用了SSR。

1 个答案:

答案 0 :(得分:0)

深入研究文档后,意识到存在一些误解。因此,如果数据需要存在于页面源中,则需要由服务器预先呈现。

为什么我问这个问题时没有显示?因为,由于页面源仅呈现静态内容,因此正在运行时评估数据。

电极已经提供了一种抽象,正在渲染的每个组件都可以选择加载预提取的数据。这里的问题是,您必须评估在运行时需要显示什么所有数据,因为更多数据与页面加载时间成正比(因为服务器将无法解析,除非您依赖的api返回成功还是失败

在实现方面,每个路由都有一个名为init-top的参数,该参数在您的页面加载之前执行。

const routes = [
  {
    path: "/",
    component: withRouter(Root),
    init: "./init-top",
    routes: [
      {
        path: "/",
        exact: true,
        component: Home,
        init: "./init-home"
      },

init-home中,您可以在-

的行上对其进行定义。
import reducer from "../../client/reducers";
const initNumber = async () => {
  const value = await new Promise(resolve => setTimeout(() => resolve(123), 2000));
  return { value };
};
export default async function initTop() {
  return {
    reducer,
    initialState: {
      checkBox: { checked: false },
      number: await initNumber(),
      username: { value: "" },
      textarea: { value: "" },
      selectedOption: { value: "0-13" }
    }
  };
}

因此,现在无论何时加载组件,它都将以initialState返回的init-home加载

如果有人被卡住,我将其张贴在这里。

相关问题