Ich habe eine funktionale Komponente, die ich in eine klassenbasierte Komponente konvertieren möchte, weil sie zu groß wurde. Ich habe ein Problem mit der Konvertierung der mapStateToProps
Funktion, kann nicht wirklich herausfinden, wie die Benutzerdaten abrufen.React.js + Flow: Funktionskomponente in klassenbasierte Komponente konvertieren
Ich benutze react-redux und 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>
)
}))
Ich möchte den obigen Code in etwas verwandeln:
// ... 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)
Mein Hauptproblem ist, dass ich nicht herausfinden können, wie die Daten die für einen Benutzer zu bekommen Komponente über mapStateToProps
.
'mapStateToProps' ist die gleiche Methode unabhängig von der Komponentenimplementierung (funktional oder nicht). – mersocarlin
Sie fehlen reducers.Wie verwalten Sie den Status –
** Problem gefunden **: Beim Importieren der neuen Komponente habe ich nicht verbundene Komponente importiert: 'Import {ContactUser} von './Contact-user' anstelle von' Importieren Sie ContactUser von './contact-user', was funktioniert. – abpetkov