【问题标题】:where to put codes I wrote in render()将我在 render() 中编写的代码放在哪里
【发布时间】:2018-03-01 00:01:18
【问题描述】:

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

【问题讨论】:

  • 这不是你应该设置状态的方式。你甚至不应该在render 中设置状态,它是零意义的。

标签: node.js reactjs react-redux recompose


【解决方案1】:

您不应在 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/

【讨论】:

    最近更新 更多