![](/img/trans.png)
[英]state management in vue js with multiple if condition to fetch data using ID
[英]SSR with data fetch without state management library
我正在尝试制作一个 SSR 反应应用程序,但无法将道具从 express 传递到组件。 我在做什么错?
服务器.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,this.props, this.props.staticContext) 我正在从服务器发送数据。 js(快递)
您的道具已经传递给 Page2 上的组件,但您渴望使用永远不会被调用的 function,
componentDidMount()
在组件安装后立即调用(插入到 DOM 树中)。
在您的情况下,您没有将任何东西安装到 DOM,因为 react 只会将您的组件渲染到 html 并且不会等待您的组件安装,实际上您的 NodeJs 服务器中没有 DOM,而您只是渲染组件并将其作为字符串返回,而不是将其插入 DOM。
你的道具已经在那里,你可以在你的 class 构造函数和你的渲染方法中控制台记录它们:
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,this.props, this.props.staticContext)
return(
<Wrapper>
<Title>This is project 01 </Title>
</Wrapper>
)
}
}
在这个 state 中,您的组件将挂载而不是挂载,您也可以使用UNSAFE_componentWillMount
控制台记录您的道具,但顾名思义,它是不安全的ReactJS.org
您还可以创建自己的函数,它会起作用:
myFunction () {
console.log(this.props.state)
}
myFunction();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.