我有一个功能组件,我想将其转换为基于类的组件,因为它太大了。我在转换mapStateToProps
函数时遇到问题,无法真正弄清楚如何获取用户数据。
我正在使用react-redux和Flow。
import { connect } from 'react-redux'
import moment from 'moment'
import 'moment-timezone/builds/moment-timezone-with-data-2010-2020'
import React, { Component } from 'react'
import styles from './contact-user.scss'
import { CSSModules } from 'app/lib/css-modules'
const applyCSS = CSSModules(styles)
export const mapStateToProps = ({
user: { data: {
birthDate,
city,
firstName,
lastName,
adresses,
timeZone } }
}) => ({
birthDate: moment(birthDate).format('L'),
city,
firstName,
lastName,
adresses,
time: timeZone ? moment().tz(timeZone).format('h:mm A z') : ''
})
export const ContactUser = connect(mapStateToProps)(applyCSS(({
adresses,
time
}) => {
const addressDetails = () => {
...
}
const sortAddresses = (a, b) => {
...
}
const handleButtonClick = (phoneType) => {
...
}
return (
<div>
<h1>Contact the User</h1>
<div className='text-center'>
{
Object.keys(adresses).length
? <MyComponent
data={adresses.sort(sortAddresses)}
/>
: <h2>No Adresses</h2>
}
</div>
{time}
...
</div>
)
}))
我想将上面的代码变成这样的代码:
// ... imports
import type { ActionCreator } from 'redux'
import type { Participants$PhonesModel } from '<coaching>/types/participants'
type State = {
ContactUser: {
birthDate: moment(birthDate).format('L'),
city,
firstName,
lastName,
adresses,
time
},
...
}
type Props = {
// ... props
} & State
export class ContactUser extends Component {
props: Props;
// methods, etc.
render () {
return (
<div>
...
</div>
)
}
}
const mapStateToProps = ({state: State}) => {
return {
...
}
}
const mapDispatchToProps = { markPhoneAsInvalid, markPhoneAsValid }
export default connect(mapStateToProps, mapDispatchToProps)(ContactUser)
我的主要问题是我无法弄清楚如何通过mapStateToProps
将用户的数据传输到组件。
答案 0 :(得分:0)
mapStateToProps
实施是一样的。在任何情况下:
class ContactUser extends Component {
render() {
...
}
}
const mapStateToProps = (state) => {
const {
birthDate,
city,
firstName,
lastName,
addresses,
timeZone,
} = state.user.data
return {
birthDate: moment(birthDate).format('L'),
city,
firstName,
lastName,
adresses,
time: timeZone ? moment().tz(timeZone).format('h:mm A z') : ''
}
}
const mapDispatchToProps = () => { ... }
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ContactUser)