简体   繁体   English

React SSR根据API响应动态导入组件

[英]React SSR dynamically import components according to API response

I am building SSR React app with razzle tool. 我正在使用Razzle工具构建SSR React应用。 Server is using express framework. 服务器正在使用快速框架。 I would like to load React components dynamically according to value included in API response. 我想根据API响应中包含的值动态加载React组件。

I have folder structure like: 我的文件夹结构如下:

views 意见
- default -默认
-- Home.js -Home.js
- theme1 -theme1
-- Home.js -Home.js

I am using SSR. 我正在使用SSR。 On the server I have 在服务器上我有

const markup = renderToString( 
<Provider store={store}> 
   <StaticRouter context={context} location={req.url}> 
      <App theme={theme} /> 
   </StaticRouter> 
</Provider> 
);

Inside App component, I need to import component from corresponding subfolder or if its absent than import default component from the default subfolder. App组件内部,我需要从相应的子文件夹中导入组件,或者如果不存在,则需要从默认子文件夹中导入默认组件。 There can be many theme subfolders so I can't import all the components manually. 可以有很多主题子文件夹,所以我不能手动导入所有组件。

Should this by done on server by express or is there another way? 应该通过快递在服务器上完成还是还有其他方法?

Thanks 谢谢

Are you looking for something like this? 您是否正在寻找这样的东西? I'm not quite sure if you are using server side rendering. 我不太确定您是否正在使用服务器端渲染。

import DefaultComponent from './views/default.js';
import Theme1Component from './views/theme1.js';

this.state = {
     visibleDefault: true
}

You can then simply update the state base on the response. 然后,您可以简单地根据响应更新状态。

Then in your render you can have this 然后在您的渲染中可以有这个

render(){
    return(
       { visibleDefault ? <DefaultComponent/> : <Theme1Component/> }
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM