【问题标题】:react native TypeError attempted to assign to readonly property反应原生 TypeError 试图分配给只读属性
【发布时间】:2020-10-21 03:25:10
【问题描述】:

您好,我是新手,我尝试在 react native 中使用 socketio 发送套接字,但我收到错误:typeerror 试图分配给 ConnectScreen.js 中的只读属性它没有说明哪一行,请知道我做错了什么?

在 web 博览会中它说:无法添加属性更新程序,对象不可扩展 在移动设备上的博览会上说:试图分配给 ConnectScreen.js 中的只读属性(由 SceneView 创建)

import React from 'react';
import {View, Text, StyleSheet, Button, TextInput, TouchableHighlight} from 'react-native';
import socketIO from 'socket.io-client';
import io from 'socket.io-client';

export default class ConnectScreen extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            ip: "localhost", //ip rpi 192.168.1.172
            connecting: false,
        }

        return(
            <View style={styles.container}>
                <Text style={styles.txt}>Connect to IP:</Text>
                <TextInput
                    style={{ height: 60, borderColor: 'gray', borderWidth: 1 }}
                />
                <TouchableHighlight style={styles.button} activeOpacity={0.6} underlayColor="#DDDDDD" onPress={this.connectWifi()}>
                    <Text style={styles.txt}> CONNECT </Text>
                </TouchableHighlight>
            </View>
        );

    }

    connectWifi(){
        let socketIO = io("http://"+this.state.ip+":8888", {transports:['websocket']});
        this.setState({connecting:true});
        console.log("connecting to http://"+this.state.ip+":8888 ...");

        socketIO.on('connection_successful', () =>{
            this.props.navigation.navigate('Main', {socketIO, ip:this.state.ip});
            this.setState({connecting:false});
        });

        //checking if connection with server was succesfull
        setTimeout(() =>{
            if(this.state.connecting){
                this.setState({connecting:false});
                socketIO.disconnect();
                console.log("connection failed");
            }
        },3500);
    }


}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        width: "50%",
        alignSelf:'center',
        
  },
    button:{
        alignSelf:'center',
        backgroundColor: "#89cff0",
        width: "100%",
        
    },
    txt:{
        alignSelf:'center',
        fontSize: 50,

    }
});

【问题讨论】:

    标签: react-native


    【解决方案1】:

    将构造函数中的return语句移到render方法中。

    React 类组件应该有 render() 方法。当状态改变时,React 会调用你的 render() 方法。

    【讨论】:

    • 谢谢,我是这样重写的,但现在我得到了新的错误,不变违规:超出最大更新深度,当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时会发生这种情况,我看到我使用了多个 setState 但它来自指南如何实现 socketio:/ 更新 ConnectScreen.js:pastebin.com/3x95AMza
    • 已修复,this.connectWifi 有问题,我必须删除 ()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 2020-04-08
    • 2016-07-19
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多