问题
I am new to React, so please don't judge strictly. I am rendering my React app on server and want execute code on frontend side. Application renders properly with styles and without warnings or errors, though with empty state since I am using API which should execute on front side and it is OK for now.
as I understand server renders component and since server rendered and mounted component on server and it is not calling componentDidMount()
method
which should do my API calls and other staff
this is my component
import React from 'react';
import {render} from 'react-dom';
import SpComparison from './spComparison.jsx';
import Comparison from './comparison.jsx';
import AnalystRatings from './analystRatings.jsx';
export default class Insights extends React.Component {
constructor(props){
super(props);
this.state = {
charts: []
}
let _this = this;
}
componentDidMount() {
console.log("I want to do log on front end side, but can't")
}
render () {
let charts = this.state.charts.map(function(i){
if (i.type == 'comparison'){
return <Comparison key={ i.id } config={ i.config } />
}
else if (i.type == 'sp-comparison'){
return <SpComparison key={ i.id } config={ i.config } />
}
if (i.type == 'analyst-ratings'){
return <AnalystRatings key={ i.id } config={ i.config } />
}
});
return (
<div id="insights" className="container">
<div className="row">
<div className="col-md-3 hidden-md-down" style={{
marginTop: 10
}}>
<ul className='finstead-tabs'>
<li className="finstead-tabs-header">
Categories
</li>
<li>
<a href='' className="finstead-active-tab">Performance</a>
</li>
<li>
<a href=''>Financial</a>
</li>
<li>
<a href=''>Valuation</a>
</li>
<li>
<a href=''>Shares</a>
</li>
<li>
<a href=''>Outlook</a>
</li>
</ul>
</div>
<div className="col-xs-12 col-md-9">
{ charts }
</div>
</div>
</div>
)
}
}
I guess I am doing it not right way, so please help me.
NOTE
In highest level component I haven't called ReactDOM.render
may it cause this behaviour?
tutorial that I used for example
回答1:
I have found solution after reading tutorial more carefully.
Problem was my inattention and everything is described in tutorial above.
basically in bundled file you should call ReactDOM.render
to execute application again, but it won't affect on performance since React uses VirtualDOM and diffing with already existing DOM.
so without ReactDOM.render
js won't be executed.
so I created separate file app-script.js
which is my entry point for bundle and it calls my highest component with ReactDOM.render
.
来源:https://stackoverflow.com/questions/41421060/reactjs-server-side-rendering-and-componentdidmount-method