把我写的代码放在render()的哪里

时间:2017-09-20 04:33:06

标签: node.js reactjs react-redux recompose

我正在尝试迁移到重新构建,但我有点困惑: 我通常在render()方法的开头写一些代码,例如检查值,设置样式,...... 如果我使用recompose我可以在哪里编写这些代码? 例如:

render() {
        const { classes } = this.props;

        var startPos;
        if (this.props.isGeolocationAvailable && this.props.isGeolocationEnabled && this.props.coords != undefined) {
            console.log("location : " + this.props.coords.longitude + ":" + this.props.coords.latitude)
            this.state.initial_location = this.props.coords;
        }
        else {
            this.state.initial_location = { longitude: 0, latitude: 0 };
        }
...

1 个答案:

答案 0 :(得分:2)

您不应在render()函数中设置或修改任何react状态。 我建议你在构造函数中做这些东西(道具) 喜欢

constructor(props){
  super(props);
  let isGeoAvailable = this.props.isGeolocationAvailable && this.props.isGeolocationEnabled && this.props.coords != undefined;
  this.state = {
    initial_location: isGeoAvailable ? this.props.coords : { longitude: 0, latitude: 0 }
  }
}

对于使用重构,您可能想要像这样分开

import { compose } from 'recompose';

const withGeoAvailable = (Component) = (props) => (
  props.isAvailable ? <Component {...props} /> : <p>GeoLocation is not available</p>
);

let enhancer = compose(withGeoAvailable)

let EnhancedMapComponent = enhancer(YourMapComponent)

render() {
  return <EnhancedMapComponent isAvailable={this.state.isAvailable} />
}

顺便说一句,我建议你阅读这篇文章,他只是解释了更高阶的组件。 https://www.robinwieruch.de/gentle-introduction-higher-order-components/