gpt4 book ai didi

javascript - ReactDOM.hydrate() 在初始 SSR 后不工作(React JS)

转载 作者:行者123 更新时间:2023-11-30 06:21:27 26 4
gpt4 key购买 nike

在我对应用程序进行初始服务器端呈现后,我的 onClick 事件(在我的 Homepage.js 组件中的按钮上)没有执行。我的 client.js 文件中的 ReactDom.hydrate() 似乎不起作用。任何帮助将不胜感激!您可以转到以下存储库以获取整个代码库 https://github.com/thegreekjester/React_SSR .

运行和重现问题的步骤:

  • npm 安装
  • npm 运行开发
  • 在浏览器中打开localhost:3000
  • 点击出现的按钮
  • 您应该在控制台中看到一些消息,但您没有看到

主页.js:

import React from 'react'
import {connect} from 'react-redux'

class HomePage extends React.Component{

exampleMethod(){
console.log('Shit is going down')
}

render(){
return(
<div>
<h1>{this.props.state.attributes.name}</h1>
<button onClick={() => this.exampleMethod()}> Console log some text </button>
</div>
)
}
}

const mapStateToProps = (state) => ({state:state.optimizelyReducer});

const mapDispatchToProps = (dispatch) => ({
dataFileManager: (timing, id, attributes) => dispatch({type:'USER_SERVICE', id:id, attributes:attributes},
dispatch({type:'DATAFILE_MANAGER', timing:timing})),
updateAttr: (attr) => dispatch({type:'UPDATE_ATTR', attr:attr, value:value})
});

HomePage = connect(mapStateToProps, mapDispatchToProps)(HomePage);



export default HomePage;

客户端.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import { Provider as ReduxProvider } from 'react-redux'
import App from './App.js'
import configureStore from './store/configureStore';

const preloadedState = window.__PRELOADED_STATE__

const store = configureStore(window.__PRELOADED_STATE__);

ReactDOM.hydrate(
<ReduxProvider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</ReduxProvider>,
document.getElementById('root')
);

服务器.js:

import 'babel-polyfill'
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter } from 'react-router'
import bodyparser from 'body-parser'
import App from './src/App.js'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import configureStore from './src/store/configureStore.js'


const app = express();
const PORT = process.env.PORT || 3000


app.use(bodyparser.json());

app.use(express.static('build/public'));

function handleRender(req, res){
const store = configureStore()
const context = {}
const html = ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<App/>
</StaticRouter>
</Provider>
)

const preloadedState = store.getState()
res.send(renderFullPage(html, preloadedState))
}

function renderFullPage(html, preloadedState){
return `
<html>
<head>
</head>
<body>
<div id='root'>${html}</div>
<script>window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}</script>
<script type='babel' src='client_bundle.js'></script>
</body>
</html>`

}

app.use(handleRender)



app.listen(PORT, () => {
console.log(`React SSR App is running on port ${PORT}`)
});

Webpack.client.js

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');

module.exports = {

// production || development
mode: 'development',

// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',

// Tell webpack the root file of our
// server application
entry: './src/client.js',

// Tell webpack where to put the output file
// that is generated
output: {
filename: 'client_bundle.js',
path: path.resolve(__dirname, 'build/public'),
publicPath: '/build/public'
},
module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: 'web'
}]
]
}
}
]
}
};

Webpack.server.js

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');

module.exports = {

// production || development
mode: 'development',

// Inform webpack that we're building a bundle
// for nodeJS, rather then for the browser
target: 'node',

// Tell webpack the root file of our
// server application
entry: './server.js',

// Tell webpack where to put the output file
// that is generated
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/build'
},

module: {
rules: [
{
test: /\.js?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
options: {
presets: [
'react', 'stage-0', ['env', {
target: { browsers: ['last 2 versions']}
}]
]
}
}
]
},

// Tell webpack not to bundle any libraries that exist in the 'node_modules' folder
// into the server bundle
externals: [webpackNodeExternals()]

};

最佳答案

有几点你必须检查:

  • 你为什么使用 target: 'node'在你的客户端 webpack 配置中?
  • <script type='babel' src='client_bundle.js'></script> 怎么了? ?为什么要输入 babel?
  • 您可能还需要babel-polyfill在您的客户端条目中,具体取决于您编译 javascript 的方式。

关于javascript - ReactDOM.hydrate() 在初始 SSR 后不工作(React JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52810335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com