【发布时间】:2017-03-30 22:37:44
【问题描述】:
我有一个名为Volume 的无状态功能组件,它使用connect() 创建容器组件:
const mapStateToProps = (state) => ({
volume: state.get('volume')
})
let Volume = (props) => {
if (props.volume === 'Infinity') {
return (
<Text
style={{ ...formStyles.text, ...styles.text }}>
Incalculable
</Text>
)
} else {
return (
<Text
style={{ ...formStyles.text, ...styles.text }}>
{props.volume + ' litres'}
</Text>
)
}
}
Volume.propTypes = {
volume: React.PropTypes.string
}
Volume = connect(
mapStateToProps,
null
)(Volume)
export default Volume
我现在需要在其上实现 componentDidMount 生命周期方法,该方法将运行一个将整个 redux 存储作为参数的函数,然后调度一个操作来更新 store.volume,然后可以将其传递给初始卷要显示的表示组件。所以我想回归基础,不使用connect(),这样我就可以在容器组件中实现生命周期方法。我从来没有用过connect()
这是我的尝试:
import { Text } from 'react-native'
import React, { Component } from 'react'
import { formStyles } from '../../style'
import calcVol from '../../calcVol'
import { updateVolume } from '../../actions/updateDimension.action'
export class VolumeContainer extends Component {
componentDidMount() {
const { store } = this.context
this.unsubscribe = store.subscribe(() =>
this.forceUpdate()
)
let litres = calcVol(store)
store.dispatch(updateVolume(litres))
}
componentWillUnmount() {
this.unsubscribe()
}
render() {
const { store } = this.context
return (
<VolumePresentational volume={store.getState().volume} />
)
}
}
VolumeContainer.contextTypes = {
store: React.PropTypes.object
}
let VolumePresentational = (props) => {
if (props.volume === 'Infinity') {
return (
<Text
style={{ ...formStyles.text, ...styles.text }}>
Incalculable
</Text>
)
} else {
return (
<Text
style={{ ...formStyles.text, ...styles.text }}>
{props.volume + ' litres'}
</Text>
)
}
}
VolumePresentational.propTypes = {
volume: React.PropTypes.string
}
const styles = {
text: {
marginTop: 20,
fontSize: 30,
fontWeight: 'bold'
}
}
export default VolumeContainer
代码进入了我的 volCalc(store) 函数,其中出现错误:
state.get 不是函数
所以我在 componentDidMount 中传递给 calcVol() 的商店一定不是商店。
我做错了什么?
【问题讨论】:
-
我不明白你为什么要将一些商店数据拉入组件(
volume),当组件挂载时在那里修改,然后将其发送回商店?calcVol函数在做什么? -
@AlexYoung calcVol 计算给定商店的交易量。该应用程序非常面向数学,因此商店仅包含执行计算所需的东西。我想在应用程序首次启动时进行初始计算,这将计算并显示音量
标签: reactjs react-native redux react-redux