2017-06-20 36 views
0

我正在編程一個應用程序,以瞭解websocket如何反應本機。 我已經從JSON格式的websocket獲取數據,我可以在console.log中的控制檯中打印它們,但是我想只在按鈕上放置JSON對象的一部分,例如,如果我的JSON對象看起來像像這樣:React Native在按鈕上實現JSON字符串

var myJSON = '{"Question": "Want to join?", "Answer":"yes" }'; 

所以我想寫的字符串「想加入?」在按鈕上。我在下面的代碼中試過,但是我得到的錯誤:undefined不是一個對象(評估'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爲什麼我不能在我的按鈕顯示其轉換。謝謝你的幫助!

回答

0

您正確解析JSON對象。由此產生的myObj是一個JavaScript對象,所以你可以直接使用它的值來訪問它的值。 myObj.Question。要設置組件的狀態,使用setStatecomponentDidMount

ws.addEventListener('message', function (event) { 
    console.log('Message from server', event.data); 
    var myObj = JSON.parse(event.data); 
    this.setState({text: myObj.Question}); 
} 

我沒有親自建成使用WebSockets什麼在RN但作爲一般原則,任何聽衆componentDidMount設立應componentWillUnmount被刪除。

+0

this.setState給我的錯誤:this.setState不是函數 – Hang

+0

可能是因爲'this'是錯誤的。嘗試在啓動事件偵聽器並使用self.setState({text:myObj.Question});'之前設置'let self = this;'在componentDidMount中。那樣有用嗎? – NiFi

+0

是的,它的功能!謝謝! – Hang

相關問題