2017-08-03 28 views
1

我試圖創建一個小應用程序,但有很多問題) 我有3個屏幕並使用react-navigation來傳遞數據。方案如下:React Native:在屏幕之間傳遞數據

1) loading screen (fetch data and save it to AsyncStorage+handling data and save to obj1 for pickers) 
(pass obj1) 
2)main screen (get data,render pickers based on it, take selected values and pass them next) 
(pass pickers selection+input) 
3)some results(get data from Asyncstorage, some calculating and render results) 

所以我有兩個問題。

當我從3)導航回2)我有一個錯誤,screen2需要數據,從screen1傳遞。是的 - 我已經檢查,如果這個數據傳遞到3,然後到2,當後退按鈕被按下,並沒有錯誤,但我敢肯定這是不好的解決方案

和second..trying解釋)on屏幕3對採摘選擇進行了一些計算,所以它沒有問題。但其他人需要從AsyncStorage獲取數據,然後根據Picker值將其轉換爲ListView。儘管我正在從componentWillMount獲取AS,但它仍需要很長時間,所以渲染數據是不確定的。當然我使用的是國家,但我認爲這是一個不好的數據處理邏輯。它定義爲第一個加載視圖(我使用導航器的堆棧屏)

export default class App extends Component { 
    constructor(props) { 
     super(props); 

     }; 
    } 
    myCallback(dataFromChild) { 
     console.log("yeah", dataFromChild); 

    } 

    render() { 
    return (
     <LoadingScreen callbackFromParent={this.myCallback}/> 
    ); 
    } 
} 

和LoadingScreen.js:

render() { 
    return(
     <View style={{flex: 1, backgroundColor: '#dc143c', marginTop:20}}> 
      <Image 
       source={require('./WhiteLogo.png')} 
       style={{flex:3, height: undefined, width: undefined, marginLeft:20, marginRight:20}} 
       resizeMode="contain" 
       qwer={this.props.callbackFromParent('listInfo').bind(this)} 
      /> 
      <Spinner color='white' style={{flex:1}}/> 
     </View> 
    ); 
    } 
} 

,我已經得到了一個錯誤「未處理的異常JS:this.props。 callbackFromParent不是一個函數「

+0

什麼是導航從SCREEN3回畫面2的錯誤?反應 - 本地只是保持其從screen1傳遞的以前的狀態,是不是夠了?或者你的意思是在screen3中你改變了一些東西,然後需要相應地更新screen2? – Val

+0

screen3邏輯,如果你真的有太多的數據基於screen2選擇器,並需要長時間計算,這將是多久? 「ActivityIndi​​cator」足夠嗎? – Val

+0

@Val所以當screen2加載它時需要screen1中的一些對象與數據。當我使用back3按鈕從screen3到screen2出現像「對象未定義」的錯誤。當我將這個obj從screen2傳遞給screen3(它實際上並不需要它),然後以相同的名稱返回screen3時,錯誤消失了。這是不好的解決方案,現在我試圖把它傳遞給屏幕的父母,但也有一些問題(已更新問題) – nastassia

回答

1

AsyncStorage可能不是您嘗試的最佳解決方案。數據傳輸使用react-navigation也不是最好的。我會建議檢查全局存儲狀態的redux,並在需要時將其傳送到頁面。還有一種方法是將函數傳遞給子組件的道具,以將任何數據從子組件提取出來。您可以檢查thisthis或示例代碼如下。

家長

class Parent extends Component { 
    updateState (data) { 
     this.setState(data); 
    } 
    render() { 
     <View> 
      <Child updateParentState={this.updateState.bind(this)} /> 
     </View> 
    } 
} 

兒童

class Child extends Component {  
    render() { 
     <View> 
     <Button title="Change" onPress={() => {this.props.updateParentState({name: 'test})}} /> 
     </View> 
    } 
} 
+0

謝謝,我試圖將從孩子傳遞給父母,我有一個錯誤_Unhandled JS異常:this.props.callbackFromParent不是一個函數_,你能否請檢查我的代碼上面? – nastassia

相關問題