使用connect()创建的容器组件上的生命周期方法调用

时间:2017-03-30 21:19:46

标签: reactjs react-native redux react-redux

我想在componentDidMount() ed组件创建的容器组件上调用connect()

import { View, Text } from 'react-native'
import { connect } from 'react-redux'
import { formStyles } from '../../style'
import { DimenInput } from '../dimenInput/DimenInput'
import { updateDimension } from '../../actions/updateDimension.action'
import React from 'react'
import { updateVolume } from '../../actions/updateDimension.action'
import calcVol from '../../calcVol'

const mapStateToProps = (state) => ({
  height1: state.get('height').get('height1').toString(),
  height2: state.get('height').get('height2').toString()
})

const updateHeight = (text, number) => (dispatch, getState) => {
  dispatch(updateDimension('height', text, number))
  let litres = calcVol(getState())
  dispatch(updateVolume(litres))
}

let Height = (props) => (
  <View style={formStyles.container}>
    <DimenInput
      value={props.height1}
      onChangeText={text => props.updateHeight(text, 1)}
    />
    <Text style={formStyles.text}>{'FT'}</Text>
    <DimenInput
      value={props.height2}
      onChangeText={text => props.updateHeight(text, 2)}
    />
    <Text style={formStyles.text}>{'IN'}</Text>
  </View>
)
Height.propTypes = {
  height1: React.PropTypes.string.isRequired,
  height2: React.PropTypes.string.isRequired,
  updateHeight: React.PropTypes.func.isRequired
}

Height = connect(
  mapStateToProps,
  { updateHeight }
)(Height)

export default Height

有可能吗?我尝试使用connect(),因为它做了一些性能优化。或者我只需要手动创建容器组件来添加生命周期方法吗?

这样做的主要目的是我需要在app启动时调用一个方法。不在组件启动时。因此,如果还有其他方法可以做到这一点,那么我有兴趣了解它。 There is a good way to do it with react router onEnter()但是我没有反应路由器,因为它是单页应用程序所以没有路由。

1 个答案:

答案 0 :(得分:0)

如果要访问React组件的生命周期方法,则需要使用从React.Component扩展的对象。您可以通过使用React.createClass或ES6类表示法创建组件来实现此目的,而不是像使用箭头功能那样使用功能组件。

React top level API

var Height = React.createClass({
  componentDidMount: function(){
    //...
  }
});

ES6方法:

class Height extends React.Component {
  constructor(props) {
    //...
  }
  componentDidMount(){
     //...
  }
}
相关问题