简体   繁体   English

没有通量的同构react.js

[英]isomorphic react.js without flux

I am newbie with react.js . 我是react.js的新手。 I want to make isomorphic react.js component . 我想制作同构的react.js组件。 I wonder is it possible to make it without flux pattern ? 我想知道是否可以不使用助焊剂模式? Now I have little component and there is api fetch method inside component and as it seems this api call runs twice :( . 现在我几乎没有组件,并且组件内部有api fetch方法,并且看来此api调用运行了两次:(。

For more clarity, I want to render DOM in server side , and want to handle react.js component events in browser side . 为了更加清晰,我想在服务器端呈现DOM,并希望在浏览器端处理react.js组件事件。

My component looks like : 我的组件看起来像:

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}))
    );
});

Make a parent Component whose child will be MyComponent 制作一个父组件,其子组件将为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>
    )
  }
}

Now, render your ParentComponent irrespective of the api call. 现在,无论api调用如何,都渲染您的ParentComponent。 Once, the ParentComponent is mounted, it will automatically trigger the rendering of MyComponent . 一旦安装了ParentComponent ,它将自动触发MyComponent的呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM