import React, {Component} from 'react'; import {View, StyleSheet, Dimensions, Image, ToastAndroid} from 'react-native'; import Img1 from './img/img1.png'; import Img2 from './img/img2.png'; import MyButton from '../MyButton'; import {login, logout, connect} from '../MyTest'; import {websocket} from '../MyUtilities'; const {width, height} = Dimensions.get('window'); class TwoPlayerPKHome extends Component { constructor() { super(); } componentDidMount() { login(); } componentWillUnmount() { this.cancelSearching(); // 卸载异步操作设置状态 this.setState = (state, callback) => { return; }; websocket.disconnect(); logout(); } state = {isStarted: false, isCanceling: false}; resolveMessage = msg => { const data = JSON.parse(msg.data); console.log(data); if (false) { const opponent = null; //this.props.navigation.navigate('双人PK结算'); this.props.navigation.navigate('双人PK中', {opponent: opponent}); this.setState({isStarted: false, isCanceling: false, opponent: null}); } if (data.hasOwnProperty('type') && data.type === 'MATCH_CANCEL_SUCCESS') { this.setState({isStarted: false, isCanceling: false, opponent: null}); websocket.disconnect(); } }; joinMatch = () => { this.setState({isStarted: true, isCanceling: false}); console.log('websocket 已打开'); // console.log(websocket.get().readyState); websocket.joinMatch(); }; serverOnerror = () => { console.log('websocket 发生了错误'); ToastAndroid.show('服务器发生了错误', ToastAndroid.SHORT); }; startSearching = () => { console.log(); // connect(); websocket.connect({ onopen: this.joinMatch, onmessage: this.resolveMessage, onerror: this.serverOnerror, }); }; cancelSearching = () => { this.setState({isCanceling: true}); websocket.cancelJoining(); }; render() { const {isStarted, isCanceling} = this.state; return ( {isStarted ? ( isCanceling ? ( ) : ( ) ) : ( )} ); } } const styles = StyleSheet.create({ container: { backgroundColor: '#F2E2CE', //opacity: 0.5, flex: 1, }, image: { width: null, height: null, flex: 3, }, myButton: { container: { flex: 1, }, }, }); export default TwoPlayerPKHome;