将我在 render() 中编写的代码放在哪里
where to put codes I wrote in render()
我正在尝试迁移到 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() 函数中设置或修改任何反应的状态。
我建议你在 constructor(props) 中做这些事情
喜欢
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 }
}
}
为了使用recompose,你可能想像这样分开
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/
我正在尝试迁移到 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() 函数中设置或修改任何反应的状态。 我建议你在 constructor(props) 中做这些事情 喜欢
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 }
}
}
为了使用recompose,你可能想像这样分开
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/