Ich habe react-native Code mit Mobx wie unten, wie Sie sehen, ich brauche Referenz this.props.store.user.avatar
, um tiefen Objektwert von Requisiten zu bekommen, ich will nicht die lange Syntax wiederholt verwenden, ich weiß, ich kann es eine Instanz sein lassen Variable im Konstruktor für Beispiel2, aber ich finde, das ist ein Anti-Muster durch die posts, es tritt tatsächlich einige Nebeneffekt von meinem Experiment Ursache der Konstruktor nur einmal ausführen, wenn Komponenten initial, so verwende ich die dritte Möglichkeit für Beispiel3, wie Sie möchten Ich erstelle Funktion in Komponenten und gebe den Wert durch die lange Syntax zurück, das ist, was ich in meiner besten Weise tun kann, aber ich mag diesen Weg nicht, er sieht nicht elegant aus, also hat jemand bessere Vorschläge oder Lösungen/Wege?Wie reduziert man die repeat object.chain in react-native?
Example1: Meine Frage
@observer
export default class Profile extends Component {
constructor(props) {
super(props);
}
render() {
return(
<BasicInfo
avatar = { this.props.store.user.avatar }
displayName = { this.props.store.user.displayName }
location = { this.props.store.user.location }
/>
)
}
}
Example2: Anti-Muster
@observer
export default class Profile extends Component {
constructor(props) {
super(props);
this.avatar = this.props.store.user.avatar
this.displayName = this.props.store.user.displayName
this.location = this.props.store.user.location
}
render() {
return(
<BasicInfo
avatar = { this.avatar }
displayName = { this.displayName }
location = { this.location }
/>
)
}
}
Example3: Anti-Muster
@observer
export default class Profile extends Component {
constructor(props) {
super(props);
this.state = {
avatar: this.props.store.user.avatar,
displayName: his.props.store.user.displayName,
location: this.props.store.user.location,
}
}
render() {
return(
<BasicInfo
avatar = { this.state.avatar }
displayName = { this.state.displayName }
location = { this.state.location }
/>
)
}
}
Beispiel 4: Es funktioniert, aber gibt es eine bessere Art und Weise?
@observer
export default class Profile extends Component {
constructor(props) {
super(props);
}
avatar(){ return this.props.store.user.avatar}
displayName(){ return this.props.store.user.displayName}
location(){ return this.props.store.user.location}
render() {
return(
<BasicInfo
avatar = { this.avatar() }
displayName = { this.displayName() }
location = { this.location() }
/>
)
}
}
Beispiel 5: Dies ist ein guter Weg, aber es funktioniert nicht auf Rückruf
@observer
export default class Profile extends Component {
constructor(props) {
super(props);
}
callback =() => {
Actions.aboutMeEdit({ avatar: user.avatar })
// there are not work
}
render() {
const { user } = this.props.store;
return(
<BasicInfo
avatar = { user.avatar }
displayName = { user.displayName }
location = { user.location }
callback = { this.callback }
/>
)
}
}
Vielleicht 'render() {const u = this.props.store.user; Rückgabe (/ * prop = u.avatar * /); } '? – user3297291