0
我有一個功能組件,我想將其轉換爲基於類的組件,因爲它太大了。我在轉換mapStateToProps
函數時遇到問題,無法真正弄清楚如何獲取用戶數據。React.js + Flow:將功能組件轉換爲基於組件的類
我正在使用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
。
無論您的組件實現(功能與否),'mapStateToProps'都是相同的方法。 – mersocarlin
你錯過了redurs.How你會去管理狀態 –
**發現問題**:當導入新組件時,我從'。/ contact-user'導入未連接的組件:'import {ContactUser},而不是'從'。/ contact-user'中導入ContactUser,它工作。 – abpetkov