简体   繁体   中英

isomorphic react.js without flux

I am newbie with react.js . I want to make isomorphic react.js component . 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 :( .

For more clarity, I want to render DOM in server side , and want to handle react.js component events in browser side .

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

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. Once, the ParentComponent is mounted, it will automatically trigger the rendering of MyComponent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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