反应原生 |重新渲染时重新加载 websocket

时间:2021-06-15 20:56:14

标签: reactjs react-native websocket react-hooks react-functional-component

我正在使用 websocket 构建有关智能家居的小型应用程序。当我按下设备图标来切换它时,websocket 会发送消息并更新状态设备是否启用。问题是更新组件后,它会创建新的 websocket 连接,而不是保存旧的连接。任何人都可以提供一些建议吗?我做错了什么?最好使用其他 npm lib?这是代码:

`

import React, { useRef, useState,useEffect } from 'react'
import { StyleSheet, Text, View, Pressable} from 'react-native'

import LightBulbOn from '../../assets/icons/light-bulb.svg'
import Power from '../../assets/icons/power.svg'

export default function Light({ ip,id,openModal }) {

const client = React.useRef()

useEffect(() => {
    client.current = new WebSocket('ws://192.168.0.107/ws')

    client.current.onopen = (message) => {
            let data  = JSON.parse(message.data)
            alert(data)
            let arr = [...devices]
            arr[0].condition = data.light1
            arr[1].condition = data.light2
            setDevices(arr)
    }
    client.current.onmessage = message =>{
        let data  = JSON.parse(message.data)
        let arr = [...devices]
        arr[0].condition = data.light1
        arr[1].condition = data.light2
        setDevices(arr)
    }
    client.current.onerror = message =>{
        alert(message)
    } 
},[ip])
function sendMessage(id){
    if(!client.current) {
        alert('not client')
        // client.current = new WebSocket('ws://192.168.0.105/ws')
        return  
    }
    let message = devices[id].condition?'->off':'->on'
    client.current.send("light" + devices[id].id + message)
}

const [devices, setDevices] = useState([
    {
        id: 1,
        deviceName: 'ნათურა 1',
        condition: 0,
    },
    {
        id: 2,
        deviceName: 'ნათურა 2',
        condition: 0
    }
])

return (
    <View style={styles.container} >
        <Pressable style={styles.lightContainer} onLongPress={()=>openModal(id)} onPress = {()=> sendMessage(0)}>   
            <View style={styles.containerRow}>
                <LightBulbOn width='30' height='30' />
                <Power width='20' height='20' />
            </View>
            <View style={styles.description}>
                <Text style={{ fontWeight: 'bold' }}>{devices[0].deviceName}</Text>
                <Text>{devices[0].condition?'ჩართული':'გამორთული'}</Text>
            </View>
        </Pressable>
        <Pressable style={styles.lightContainer} onLongPress={()=>openModal(id)} onPress = {()=> sendMessage(1)}>
            <View style={styles.containerRow}>
                <LightBulbOn width='30' height='30' />
                <Power width='20' height='20' />
            </View>
            <View style={styles.description}>
                <Text style={{ fontWeight: 'bold' }}>{devices[1].deviceName}</Text>
                <Text>{devices[1].condition?'ჩართული':'გამორთული'}</Text>
            </View>
        </Pressable>
    </View>
)

} ` 提前致谢

0 个答案:

没有答案