我使用react-navigation來管理路由。這是我的家庭成分:用戶在React Native中按下後退按鈕時更新狀態
class HomeScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: {
firstname: 'John',
avatar: 'john-profile.png',
location: 'Canada',
}
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
render() {
return (
<View>
<Image src="{this.state.userProfile.avatar}" />
<Text>Firstname: {this.state.userProfile.firstname}</Text>
<Text>Location: {this.state.userProfile.location}</Text>
</View>
);
}
}
這是配置文件屏幕:
class ProfileScreen extends React.Component {
constructor(props) {
this.state = {
userProfile: null,
}
}
componentDidMount() {
AsyncStorage.getItem('userProfile', (errs, result) => {
this.setState({userProfile: JSON.parse(result)});
});
}
save() {
var userSavedProfile = this.state.userProfile;
userSavedProfile.firstname = "Peter";
userSavedProfile.avatar = "peter-avatar.png";
userSavedProfile.location = "EEUU";
this.setState({userProfile: userSavedProfile});
AsyncStorage.setItem('userProfile', JSON.stringify(this.state.userProfile),() => {});
}
render() {
return (
<View>
<Button title="Save" onPress={() => this.save()} />
</View>
);
}
}
當我保存新的用戶信息和我按回到標題按鈕(反應導航)的用戶配置文件老,firstname =約翰,等等......當用戶按下按鈕並刷新數據時,如何從家中更新狀態?
我也面臨着同樣的問題,但我解決它。你能告訴我,你怎麼轉移到配置文件屏幕? 家庭是配置文件屏幕的父類嗎? –
請讓我知道,然後我會在這裏發佈我的代碼。 –