带数据获取的 SSR,没有状态管理库

问题描述

我正在尝试制作一个 SSR 反应应用程序,但无法将道具从 express 传递到组件。 我做错了什么?

server.js

import AppPage2 from './src/project02/LandingPage';
......
......
server.get('/project2',async (req,res)=>{
    const context = {data:'test'}
    const sheet = new ServerStyleSheet();
    const content = ReactDOMServer.renderToString(sheet.collectStyles(
        <StaticRouter location={req.url} context={context}>
            <AppPage2 state={{"foo":"baar"}}/>
        </StaticRouter>)
    );
    const styles = sheet.getStyleTags();
    let html = appShell( 'Project 2',content,' project2.bundle.js',styles)
    res.status(200).send(html);
    res.end()
})

AppPage2(./src/project02/LandingPage)

import React from 'react';
import {Wrapper,Title}  from './styleComponent/testStylePage'
.......
.......
class AppPage extends React.Component {

    componentDidMount() {
       console.log("{{API}}",this,this.props,this.props.staticContext)
    }

    render(){
        return(
            <Wrapper>
                <Title>This is project 01 </Title>
            </Wrapper>
        )
    }
}

export default AppPage;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import AppPage from './project02/LandingPage'

ReactDOM.hydrate(
        <AppPage></AppPage>,document.querySelector('#root')
);

webpack.client.conf

const path = require('path');
const glob = require("glob");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;


const entry = glob.sync("src/*.js")
    .reduce((x,y) => Object.assign(x,{
            [y.replace('src/','').replace('.js','')]: `./${y}`,}
),{});


    
    module.exports = {
            target: 'node',mode: 'development',//development,production
            entry: entry,output: {
                filename:'[name].bundle.js',path: path.resolve(__dirname,'build/public/'),publicPath: '/build/'
            },module: {
                rules: [
                    {
                        test: /\.js$/,exclude: /(node_modules)/,use: {
                            loader: 'babel-loader'
                        },},]
            },plugins: [
                // new BundleAnalyzerPlugin()
            ]
        }

我无法从 AppPage2(./src/project02/LandingPage) 这个页面记录 console.log("{{API}}",this.props.staticContext) 我正在发送数据来自 server.js(express)

解决方法

你的 props 已经传递给你在 Page2 上的组件,但你渴望使用一个永远不会被调用的函数,

componentDidMount() 在组件安装(插入到 DOM 树)后立即调用。

在您的情况下,您没有将任何东西安装到 DOM,因为 React 只会将您的组件呈现为 html 而不会等待您的组件安装,实际上您的 NodeJs 服务器中没有 DOM,而您仅渲染组件并将其作为字符串返回,而不是将其插入到 DOM 中。

你的 props 已经存在,你可以在你的类构造函数和渲染方法中控制台记录它们:

class AppPage extends React.Component {

    constructor (props){
        super(props)
        console.log("{{API}}",this,this.props,this.props.staticContext)
    }

    render(){
        //or console log it here
        console.log("{{API}}",this.props.staticContext)
        return(
            <Wrapper>
                <Title>This is project 01 </Title>
            </Wrapper>
        )
    }
}

在这种状态下,您的组件将挂载而不是挂载,您也可以使用 UNSAFE_componentWillMount 控制台记录您的道具,但正如其名称所说,这是不安全的 ReactJS.org

您也可以创建自己的函数,它会起作用:

myFunction () {
   console.log(this.props.state)
}

myFunction();

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...