我有如下 mobx 的 react-native 代码,正如你们所看到的,我需要参考this.props.store.user.avatar
才能从道具中获取深层对象值,我不想重复使用长语法,我知道我可以让它成为构造函数中的实例变量例如2,但我发现这是posts的反模式,它实际上发生了一些副作用,因为我的实验导致构造函数在组件初始化时只执行一次,所以我使用第三种方式作为example3,如你所愿,我创建组件中的函数并通过长语法返回值,这就是我能做的最好的事情,但我不喜欢这种方式,它看起来不优雅,所以有人有更好的建议或解决方案/方式吗?
示例 1:我的问题
@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 }
/>
)
}
}
示例 2:反模式
@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 }
/>
)
}
}
示例 3:反模式
@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 }
/>
)
}
}
示例 4:它有效,但存在更好的方式?
@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() }
/>
)
}
}
示例 5:这是一个好方法,但它不适用于回调
@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 }
/>
)
}
}