嗨,我是 React 和 NodeJS 新手,我正在尝试通过 React 调用我的 NodeJS api,即使在渲染页面后,我的 componentDidMount 也根本没有被触发。 有人可以告诉我我到底在哪里失踪吗?
var React = require('react');
module.exports = React.createClass({
getInitialState: function() {
return {
jobs: []
}
},
componentDidMount: function() {
console.log("mount");
var _this = this;
this.serverRequest = $.ajax({
....
}.bind(this)
});
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div><h1>Jobs</h1>
{this.state.jobs.map(function(job) {
return (
<div key={job.id} className="job">
{job.name}
{job.address}
</div>
);
})}
</div>
)
}
});
在我以这种方式调用的 NodeServer.js 文件中,只有 Jobs 显示在我的 html 页面中
app.get('/', function(request, response) {
var htmlCode = ReactDOMServer.renderToString(React.createElement(Component));
response.send(htmlCode);
})
最佳答案
在后端渲染时,无法使用 React 组件生命周期方法加载数据,这只适用于客户端。当您在服务器上渲染组件时,它仅渲染一次,不包含数据。数据是异步加载的,当它完成时,你的组件已经被渲染了。您必须在组件外部获取数据,然后将其作为 prop 传递给组件。
关于node.js - componentDidMount 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599746/