我是react.js的新手。我想做一个同构的react.js组件。我想知道有没有可能使它没有通量模式?现在,我有了很少的组件,组件中有api提取方法,而且这个api调用运行了两次:(。
为了更清楚起见,我希望在服务器端呈现DOM,并希望在浏览器端处理react.js组件事件。
我的组件看起来像:
Class MyComponent extends React.Component{
// my component code
// components events
render() {}
}
if (!is_server()) {
apiFetch.my_api_call(function (result) {
ReactDom.render(<MyComponent data={result.data}/>, document.getElementById('navigation'))
});
}else{
apiFetch.my_api_call(function (result) {
res.status(200).send(
ReactDOMServer.renderToString(React.createElement(MyComponent, {data: result.data}))
);
});发布于 2016-04-24 11:18:24
创建其子组件为MyComponent的父组件
class ParentComponent extends React.Component {
componentDidMount() {
// make api call
apiCall.then((data) => {
this.setState({
reqData : data,
})
})
}
getComponentToRender() {
if(typeof this.state.reqData === 'undefined') {
return false;
} else {
return (
<MyComponent data={result.data}/>
)
}
}
render() {
const componentToRender = this.getComponentToRender();
return (
<div>
<componentToRender />
</div>
)
}
}现在,不管ParentComponent调用是什么,呈现您的api。一旦ParentComponent被挂载,它将自动触发MyComponent的呈现。
https://stackoverflow.com/questions/36822258
复制相似问题