2017-07-03 58 views
0

我使用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 =約翰,等等......當用戶按下按鈕並刷新數據時,如何從家中更新狀態?

+0

我也面臨着同樣的問題,但我解決它。你能告訴我,你怎麼轉移到配置文件屏幕? 家庭是配置文件屏幕的父類嗎? –

+0

請讓我知道,然後我會在這裏發佈我的代碼。 –

回答

0

我認爲您的應用程序需要一個狀態管理器,您可以在其中存儲用戶信息並在應用程序的任何位置訪問它。你應該看看Redux。它將適合您的需求,並且主屏幕上的信息會自動更新。

1

您可以使用從BackHandler反應本土 https://facebook.github.io/react-native/docs/backhandler.html 你可以改變內部的功能狀態backhandler

+0

但是在這種情況下,在ProfileScreen上使用後處理程序返回HomeScreen。在文檔中我看到不適用於iOs設備。當用戶從ProfileScreen按下返回按鈕時,我需要在Home中刷新狀態。 –

+0

從我理解你想要在HomeScreen中啓動日期狀態,從ProfileScreen中的一個動作爲此在HomeScreen中聲明一個函數,如getData()在HomeScreen getData中寫入所有邏輯,然後將其作爲道具發送給ProfileScreen並在onPress按鈕 –

相關問題