私は、websocketがどのようにネイティブに反応するかを理解するためにアプリケーションをプログラミングしています。 websocketからJSON形式でデータを取得しましたが、console.logを使って自分のコンソールに出力することができますが、JSONオブジェクトの一部だけをボタンに配置したいと思います。ボタンにJSON文字列を実装するネイティブに反応します
var myJSON = '{"Question": "Want to join?", "Answer":"yes" }';
だから私は文字列を "希望しますか?"と書いていますか?ボタン上。私は次のコードでこれを試しましたが、エラーが発生しました。未定義はオブジェクトではありません(this.state.text = JSON.stringify(myObj.Question)を評価する)
ここに私のコードはありません。スタイルシート):
import React, { Component } from 'react';
import {AppRegistry,StyleSheet,Text,View,Alert,AsyncStorage,TouchableOpacity} from 'react-native';
export default class ExampleW extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
}
}
async onButtonPressed(){
Alert.alert('The button was pressed!')
}
getText(){
return (this.state.text);
}
componentDidMount(){
var ws = new WebSocket('ws://URL');
ws.addEventListener('message', function (event) {
console.log('Message from server', event.data);
var myObj = JSON.parse(event.data);
console.log('Typ: ',myObj.Type);
console.log('Question:', myObj.Question);
this.state.text = JSON.stringify(myObj.Question);
});
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<View style ={styles.buttonContainer}>
<TouchableOpacity style = {styles.buttonAccount}
onPress = {this.onButtonPressed.bind(this)}>
<Text style = {styles.buttonText}> {this.getText()} </Text>
</TouchableOpacity>
</View>
</View>
);
}}
私が正しくJSONオブジェクトとどのようにthis.state.textに保存し、なぜ私は私のボタンに表示することはできませんが変換する方法を理解していません。助けてくれてありがとう!
this.setState私にエラーが表示されます:this.setStateは関数ではありません – Hang
「this」が間違っている可能性があります。イベントリスナーを開始する前に 'self = this;'をcomponentDidMountの中で設定し、 'self.setState({text:myObj.Question});'を使用してみてください。それは動作しますか? – NiFi
はいそれは機能します!ありがとうございました! – Hang