React-Native:导航到新屏幕后立即回到上一屏幕。使用Socket.io

时间:2019-04-24 23:30:17

标签: javascript react-native socket.io

导航到一个屏幕后,它立即返回上一个屏幕。

我正在浏览的屏幕代码:

import React, {Component} from 'react';
import {AppRegistry, View, Text, ScrollView, StyleSheet} from 'react-native';
import {CardFlip1} from '../components/CardFlip1';
import {CardFlip2} from '../components/CardFlip2';
import colors from '../config/colors';
import {PrimaryButton} from '../components/PrimaryButton';
import AsyncStorage from '@react-native-community/async-storage';
import Orientation from 'react-native-orientation-locker';
window.navigator.userAgent = 'react-native';
import io from 'socket.io-client/dist/socket.io';

class judge_screen extends Component {
    constructor (props) {
        super(props);
        this.state = {
            game_round: '',
            player1: '',
            player2: '',
            label1: '',
            label2: '',
            current_user: ''
        }
    }

    componentWillMount = () => {
        this.getActives();
    }

    componentDidMount() {
        Orientation.lockToLandscape();
        this.socket = io("socket address here", {
            jsonp: false
        });
    }

    getActives = async () => {
        let user = await AsyncStorage.getItem('email');
        let player_1 = await AsyncStorage.getItem('Player1');
        let player_2 = await AsyncStorage.getItem('Player2');
        let round = await AsyncStorage.getItem('Round');

        this.setState({game_round: round});
        this.setState({player1: player_1});
        this.setState({player2: player_2});
        var label_start = "Choose ";
        var label_end = "'s fate";
        var player_1_name = this.state.player1;
        var player_2_name = this.state.player2;
        var label1_str = label_start.concat(player_1_name, label_end);
        this.setState({label1: label1_str});
        var label2_str = label_start.concat(player_2_name, label_end);
        this.setState({label2: label2_str});
    }

    player1Win = async () => {
        let host = await AsyncStorage.getItem('host');
        if (host == 'yes') {
            let user = await AsyncStorage.getItem('email');
            this.setState({current_user: user});
        } else {
            let user = await AsyncStorage.getItem('users_id');
            this.setState({current_user: user});
        }
        var user_fix = this.state.current_user;
        let player_name = await AsyncStorage.getItem('Player1');
        AsyncStorage.setItem('Winner', player_name);

        fetch('fetch address here', {
            method: 'POST',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application.json',
            },
            body: JSON.stringify({
                email: user_fix,
                Name: player_name,
                Host: host
            })
        }).then((response) => response.json())
        .then((responseJson) => {
            if (host == 'yes') {
                this.socket.emit('end_round', 'end');
                this.props.navigation.navigate('end_round_host_screen');
            } else {
                this.socket.emit('end_round', 'end');
                this.props.navigation.navigate('end_round_guest_screen');
            }
        }).catch((error) => {
            console.error(error);
        });
    }

    player2Win = async () => {
        let host = await AsyncStorage.getItem('host');
        if (host == 'yes') {
            let user = await AsyncStorage.getItem('email');
            this.setState({current_user: user});
        } else {
            let user = await AsyncStorage.getItem('users_id');
            this.setState({current_user: user});
        }
        var user_fix = this.state.current_user;
        let player_name = await AsyncStorage.getItem('Player2');
        AsyncStorage.setItem('Winner', player_name);

        fetch('fetch address here', {
            method: 'POST',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application.json',
            },
            body: JSON.stringify({
                email: user_fix,
                Name: player_name,
                Host: host
            })
        }).then((response) => response.json())
        .then((responseJson) => {
            if (host == 'yes') {
                this.socket.emit('end_round', 'end');
                this.props.navigation.navigate('end_round_host_screen');
            } else {
                this.socket.emit('end_round', 'end');
                this.props.navigation.navigate('end_round_guest_screen');
            }
        }).catch((error) => {
            console.error(error);
        });
    }

    render() {
        return (
            <ScrollView>
                <View style={{flexDirection: 'row'}}>
                    <View style={styles.container}>
                        <Text style={[styles.text]}>
                            {this.state.player1}
                        </Text>
                        <CardFlip1 />
                        <PrimaryButton
                            onPress={() => this.player1Win()}
                            label={this.state.label1}
                        >
                        </PrimaryButton>
                    </View>
                    <View style={styles.container}>
                        <Text style={[styles.text]}>
                            {this.state.player2}
                        </Text>
                        <CardFlip2 />
                        <PrimaryButton
                            onPress={() => this.player2Win()}
                            label={this.state.label2}
                        >
                        </PrimaryButton>
                    </View>
                </View>
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: colors.backgroundColor,
        margin: 10,
        paddingBottom: 5,
        borderWidth: 1,
        borderColor: colors.borderColor,
    },
    text: {
        fontSize: 18,
        color: colors.primaryText,
        marginTop: 10,
    },
    textPadding: {
        paddingBottom: 10,
    },
    headingText: {
        fontSize: 24,
        fontWeight: '500',
        color: colors.primaryText,
        margin: 10,
    },
    textMarginHorizontal: {
        marginHorizontal: 10,
    },
})

export default judge_screen;

此屏幕上的任何按钮都导航到下一个屏幕,然后我被踢回到该屏幕。这是我试图进入的下一个屏幕的代码:

import React, {Component} from 'react';
import {View, Text, ScrollView, StyleSheet, FlatList} from 'react-native';
import colors from '../config/colors';
import {PrimaryButton} from '../components/PrimaryButton';
import AsyncStorage from '@react-native-community/async-storage';
import Orientation from 'react-native-orientation-locker';
window.navigator.userAgent = 'react-native';
import io from 'socket.io-client/dist/socket.io';

class end_round_guest_screen extends Component {
    constructor (props) {
        super(props);
        this.state = {
            player_scores: [],
            game_round: '',
            winner: '',
            is_mounted: false
        }
    }

    componentDidMount() {
        this.setState({is_mounted: true});
        if (this.state.is_mounted) {
            this.getActives();
            this.getWinner();
            Orientation.unlockAllOrientations();
            this.socket = io("socket address here", {
                jsonp: false
            });
            this.socket.on('next_round', () => this.nextRound());
            this.socket.on('end_game', () => this.endGame());
        }
    }

    componentWillUnmount() {
        this.setState({is_mounted: false});
    }

    getActives = async () => {
        let round = await AsyncStorage.getItem('Round');
        this.setState({game_round: round});
    }

    getWinner = async () => {
        let user = await AsyncStorage.getItem('users_id');

        fetch('fetch address here', {
            method: 'POST',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application.json',
            },
            body: JSON.stringify({
                email: user
            })
        }).then((response) => response.json())
        .then((responseJson) => {
            this.setState({winner: responseJson});
        }).catch((error) => {
            console.error(error);
        });
    }

    nextRound = () => {
        this.props.navigation.navigate('round_start_guest_screen');
    }

    endGame = () => {
        this.props.navigation.navigate('end_game_guest_screen');
    }

    renderItem = ({item}) => {
        return (
            <View style={{flexDirection: 'row', flex: .5, justifyContent: 'space-between'}}>
                <Text style={[styles.text, styles.textPaddingHorizontal]}>
                    {item.player}:
                </Text>
                <Text style={[styles.text, styles.textPaddingHorizontal]}>
                    {item.score}
                </Text>
            </View>
        )
    }

    render() {
        return (
            <ScrollView>
                <View style={{alignItems: 'center'}}>
                    <Text style={styles.headingText}>
                        Round {this.state.game_round}
                    </Text>
                    <Text style={styles.text}>
                        {this.state.winner} wins this round!
                    </Text>
                </View>
                <View style={styles.container}>
                    <View style={{
                        width: '80%',
                        borderWidth: 1,
                        borderColor: colors.borderColor,
                        marginVertical: 5,
                    }}
                    >
                        <View style={{alignItems: 'center'}}>
                            <Text style={styles.textSubHeading}>
                                Score:
                            </Text>
                        </View>
                        <FlatList
                            data={this.state.player_scores}
                            renderItem={this.renderItem}
                            keyExtractor={(item, index) => index.toString()}
                        />
                    </View>
                </View>
            </ScrollView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: colors.backgroundColor,
        margin: 10,
        paddingVertical: 5,
        borderWidth: 1,
        borderColor: colors.borderColor,
    },
    text: {
        fontSize: 18,
        color: colors.primaryText,
        marginTop: 10,
    },
    headingText: {
        fontSize: 24,
        fontWeight: '500',
        color: colors.primaryText,
        margin: 10,
    },
    textPaddingHorizontal: {
        paddingHorizontal: 10,
    },
})

export default end_round_guest_screen;

这是我的导航路由器:

import {createStackNavigator, createAppContainer, createSwitchNavigator} from 'react-navigation';
import sign_up_screen from '../screens/sign_up_screen';
import sign_in_screen from '../screens/sign_in_screen';
import host_or_join_screen from '../screens/host_or_join_screen';
import choose_game_screen from '../screens/choose_game_screen';
import num_phones_screen from '../screens/num_phones_screen';
import select_num_players_screen from '../screens/select_num_players_screen';
import wait_for_players_screen from '../screens/wait_for_players_screen';
import player_names_screen from '../screens/player_names_screen';
import round_start_screen from '../screens/round_start_screen';
import round_start_host_screen from '../screens/round_start_host_screen';
import round_start_guest_screen from '../screens/round_start_guest_screen';
import draw_card_screen from '../screens/draw_card_screen';
import join_game_screen from '../screens/join_game_screen';
import choose_name_screen from '../screens/choose_name_screen';
import judge_screen from '../screens/judge_screen';
import player1_screen from '../screens/player1_screen';
import player2_screen from '../screens/player2_screen';
import peanut_gallery_screen from '../screens/peanut_gallery_screen';
import end_round_host_screen from '../screens/end_round_host_screen';
import end_round_guest_screen from '../screens/end_round_guest_screen';
import end_game_host_screen from '../screens/end_game_host_screen';
import end_game_guest_screen from '../screens/end_game_guest_screen';
import end_round_screen from '../screens/end_round_screen';
import end_game_screen from '../screens/end_game_screen';

const SignUpStack = createStackNavigator({
    sign_up_screen: {
        screen: sign_up_screen,
    },
    sign_in_screen: {
        screen: sign_in_screen,
    },
});

const Game1 = createStackNavigator({
    host_or_join_screen: {
        screen: host_or_join_screen,
    },
});

const Game2 = createStackNavigator({
    choose_game_screen: {
        screen: choose_game_screen,
    },
});

const Game3 = createStackNavigator({
    num_phones_screen: {
        screen: num_phones_screen,
    },
});

const Game4 = createStackNavigator({
    wait_for_players_screen: {
        screen: wait_for_players_screen,
    },
});

const Game5 = createStackNavigator({
    select_num_players_screen: {
        screen: select_num_players_screen,
    },
});

const Game6 = createStackNavigator({
    player_names_screen: {
        screen: player_names_screen,
    },
});

const Game7 = createStackNavigator({
    round_start_screen: {
        screen: round_start_screen,
    },
});

const Game8 = createStackNavigator({
    round_start_host_screen: {
        screen: round_start_host_screen,
    },
});

const Game9 = createStackNavigator({
    round_start_guest_screen: {
        screen: round_start_guest_screen,
    },
});

const Game10 = createStackNavigator({
    draw_card_screen: {
        screen: draw_card_screen,
    },
});

const Game11 = createStackNavigator({
    join_game_screen: {
        screen: join_game_screen,
    },
});

const Game12 = createStackNavigator({
    choose_name_screen: {
        screen: choose_name_screen,
    },
});

const Game13 = createStackNavigator({
    judge_screen: {
        screen: judge_screen,
    },
});

const Game14 = createStackNavigator({
    player1_screen: {
        screen: player1_screen,
    },
});

const Game15 = createStackNavigator({
    player2_screen: {
        screen: player2_screen,
    },
});

const Game16 = createStackNavigator({
    peanut_gallery_screen: {
        screen: peanut_gallery_screen,
    },
});

const Game17 = createStackNavigator({
    end_round_host_screen: {
        screen: end_round_host_screen,
    },
});

const Game18 = createStackNavigator({
    end_round_guest_screen: {
        screen: end_round_guest_screen,
    },
});

const Game19 = createStackNavigator({
    end_game_host_screen: {
        screen: end_game_host_screen,
    },
});

const Game20 = createStackNavigator({
    end_game_guest_screen: {
        screen: end_game_guest_screen,
    },
});

const Game21 = createStackNavigator({
    end_round_screen: {
        screen: end_round_screen,
    },
});

const Game22 = createStackNavigator({
    end_game_screen: {
        screen: end_game_screen,
    },
});

const AppNavigator = createAppContainer(createSwitchNavigator(
    {
        Auth: SignUpStack,
        App1: Game1,
        App2: Game2,
        App3: Game3,
        App4: Game4,
        App5: Game5,
        App6: Game6,
        App7: Game7,
        App8: Game8,
        App9: Game9,
        App10: Game10,
        App11: Game11,
        App12: Game12,
        App13: Game13,
        App14: Game14,
        App15: Game15,
        App16: Game16,
        App17: Game17,
        App18: Game18,
        App19: Game19,
        App20: Game20,
        App21: Game21,
        App22: Game22,
    },
    {
        initialRouteName: 'Auth',
    }
));

export default AppNavigator;

这是我保存socket.io服务器代码的地方:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

io.on('connection', function (socket) {
    socket.on('names', () => {
        io.emit('names')
    });
    socket.on('round_start', () => {
        io.emit('round_start')
    });
    socket.on('game_start', () => {
        io.emit('game_start')
    });
    socket.on('end_round', () => {
        io.emit('end_round')
    });
    socket.on('next_round', () => {
        io.emit('next_round')
    });
    socket.on('end_game', () => {
        io.emit('end_game')
    });
});

我正在尝试从审判者屏幕的end_round_guest_screen导航,但是被踢回到审判者屏幕。我正在使用Socket io,以便能够在多部手机上玩游戏,并在游戏中采取行动时使它们彼此实时自动更新。在执行此操作之前,所有其他屏幕转换均没有问题。是客人电话有问题;主机电话可以导航到下一个屏幕,而不会出现问题。

0 个答案:

没有答案