0

我正在尝试迁移到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 };
        }
...
4

1 回答 1

2

您不应在 render() 函数中设置或修改任何反应的状态。我建议你在构造函数(道具)中做这些事情,比如

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/

于 2017-09-20T04:57:47.080 回答