2016-09-23 2 views
0

ボタンをクリックしたときにページに新しい文字列を表示しようとしています。今すぐボタンをタップすると文字列を返すサービスが呼び出されています。これは機能し、私は警告し、値を記録することができ、私はそこに欲しいものを得ている。私はボタンをクリックすると、しかし、私はその値がページクリック時に別のコンポーネントを更新する

上に表示されるようにしたいこれは私がこれまで持っているものです。

class Status extends Component { 
    render() { 
    return (
     <Text>{this.props.status}</Text> 
    ); 
    } 
} 

class StupidStatusApp extends Component { 

    _onPressButton() { 
     return fetch('http://stupidstat.us/api/user/status') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
     console.log(responseJson.text); 
     return responseJson.text; 
     }) 
     .catch((error) => { 
     console.error(error); 
     }); 
    } 

    render() { 
    return (
     <View style={styles.container}> 
     <Status status={this._onPressButton} style={styles.welcome}> 
     </Status> 
     <TouchableHighlight style={styles.button} onPress={this._onPressButton}> 
      <Text style={styles.buttonText}>Get new stupid status</Text> 
     </TouchableHighlight> 
     </View> 
    ); 
    } 
} 

私はに値を渡しするかどうかはわかりませんし、レンダリング再すべてのボタンをクリックします。

答えて

0

ステータスを返してプロパティに割り当てるのではなく、ステータスを状態に保存し、setStateを使用して更新する必要があります。次に、あなたのStatusコンポーネントに状態を渡すことができます:

class Status extends Component { 
    render() { 
    return (
     <Text>{this.props.status}</Text> 
    ); 
    } 
} 

class StupidStatusApp extends Component { 

    _onPressButton() { 
     return fetch('http://stupidstat.us/api/user/status') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
     console.log(responseJson.text); 
     this.setState({status:responseJson.text}); // Change here 
     }) 
     .catch((error) => { 
     console.error(error); 
     }); 
    } 

    render() { 
    return (
     <View style={styles.container}> 
     <Status status={this.state.status //Change here} style={styles.welcome}> 
     </Status> 
     <TouchableHighlight style={styles.button} onPress={() => {this._onPressButton}}> // Change here 
      <Text style={styles.buttonText}>Get new stupid status</Text> 
     </TouchableHighlight> 
     </View> 
    ); 
    } 
} 
関連する問題