Переход к экрану на основе условий состояния переменных в Redux - PullRequest
0 голосов
/ 23 апреля 2020

У меня есть некоторые переменные состояния в моем редукторе (hpBar, врагибар) в моем редукторе. js файл, который использует функцию редуктора для обновления состояния в других моих трех экранах (капитан, инженер, оружие).

Если состояние hpBar или templeBar = 0. Я хочу, чтобы пользователь перемещался со своего текущего экрана на другой экран, называемый «PreGame». Как можно go сделать это?

IE: если (this.props.enemyBar <= 0 || this.props.hpBar <= 0), перейдите к screen ('PreGame') this.props.navigation.navigate ('PreGame') </strong>

В настоящее время я пробовал это, и хотя он не обрабатывает sh моей программы, на самом деле это не так перейти к нужному экрану в зависимости от состояния состояния притока.

Эти 3 экрана представляют собой разные вкладки в навигаторе нижней вкладки, содержащиеся в главном экране Game. js

Game. js

import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import * as Progress from 'react-native-progress';
import { createStore } from 'redux'
import { Provider, connect } from 'react-redux'
import CaptainScreen from '../../src/roles/Captain.js'
import WeaponsScreen from '../../src/roles/Weapons.js'
import EngineersScreen from '../../src/roles/Engineer.js'

import reducer from '../../src/store/reducer'
import { createAppContainer } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';


const store = createStore(reducer);
const TabNavigator = createAppContainer(createMaterialBottomTabNavigator(
    {
        Captain: {
            screen: CaptainScreen,
            navigationOptions: {
                tabBarIcon: ({ tintColor }) => (
                    <View>
                        <Icon name="ship-wheel" style={[{ color: tintColor }]} size={25} />
                    </View>
                ),
            }
        },
        Weapons: {
            screen: WeaponsScreen,
            navigationOptions: {
                tabBarIcon: ({ tintColor }) => (
                    <View>
                        <Icon name="pistol" style={[{ color: tintColor }]} size={25} />
                    </View>
                ),
                activeColor: '#ffffff',
                inactiveColor: '#a3c2fa',
                barStyle: { backgroundColor: '#2163f6' },
            }
        },
        Engineer: {
            screen: EngineersScreen,
            navigationOptions: {
                tabBarIcon: ({ tintColor }) => (
                    <View>
                        <Icon name="hammer" style={[{ color: tintColor }]} size={25} />
                    </View>
                ),
                activeColor: '#ffffff',
                inactiveColor: '#92c5c2',
                barStyle: { backgroundColor: '#2c6d6a' },
            }
        },
    },
    {
        initialRouteName: 'Captain',
        activeColor: '#ffffff',
        inactiveColor: '#bda1f7',
        barStyle: { backgroundColor: '#6948f4' },
    }
));


export default class Root extends Component {
    render() {

        return (
            <Provider store={store}>


                <TabNavigator >

                </TabNavigator>
            </Provider>
        );
    }

}

Редуктор. js

import { Text, View, StyleSheet } from 'react-native'
import React, { navigation } from 'react'

const initialState = {
    hpBar: 1.0,
    enemyBar: 1.0,
    engMessage: "N/A",
    wepMessage: "N/A",

};

const reducer = (state = initialState, action) => {
    const newState = { ...state };
    let rand = Math.floor((Math.random() * 100) + 1)

    switch (action.type) {
        case 'HP_UP':
            rand = Math.floor((Math.random() * 100) + 1);


            if (state.hpBar >= 1) {
                console.log('Ship fully repaired');
                return {
                    ...state,
                    hpBar: 1,
                }

            }

            else if (state.hpBar <= -0) {
                console.log('Ship unrepairable.')
                return {
                    ...state,
                    hpBar: 0
                }
            }

            if (rand <= 60) {

                console.log("repaired")
                return {
                    ...state,
                    hpBar: state.hpBar + action.payload,
                    engMessage: "Successful!"

                }
            }
            else {
                console.log("not repaired")
                return {
                    ...state,
                    engMessage: "Failed!"

                }
            }

        case 'HP_UP2':
            rand = Math.floor((Math.random() * 100) + 1);

            if (state.hpBar >= 1) {
                console.log('Ship fully repaired');
                return {
                    ...state,
                    hpBar: 1,
                }

            }

            else if (state.hpBar <= -0) {
                console.log('Ship unrepairable.')
                return {
                    ...state,
                    hpBar: 0
                }
            }

            if (rand <= 40) {

                console.log("repaired")
                return {
                    ...state,
                    hpBar: state.hpBar + action.payload,
                    engMessage: "Successful!"

                }
            }
            else {
                console.log("not repaired")
                return {
                    ...state,
                    engMessage: "Failed!"

                }
            }

        case 'HP_UP3':
            rand = Math.floor((Math.random() * 100) + 1);


            if (state.hpBar >= 1) {
                console.log('Ship fully repaired');
                return {
                    ...state,
                    hpBar: 1,
                }
            }

            else if (state.hpBar <= -0) {
                console.log('Ship unrepairable.')
                return {
                    ...state,
                    hpBar: 0
                }
            }

            if (rand <= 20) {

                console.log("repaired")
                return {
                    ...state,
                    hpBar: state.hpBar + action.payload,
                    engMessage: "Successful!"

                }
            }
            else {
                console.log("not repaired")
                return {
                    ...state,
                    engMessage: "Failed!"

                }
            }

        case 'HP_DOWN':
            rand = Math.floor((Math.random() * 100) + 1)

            if (state.enemyBar <= -0) {
                console.log('You beat the enemy');
                return {
                    ...state,
                    enemyBar: 0,
                }

            }

            else if (state.hpBar <= -0) {
                console.log('You lose!')
                return {
                    ...state,
                    hpBar: 0,


                }
            }

            if (rand >= 50) {
                //console.log("hit")
                return {
                    ...state,
                    enemyBar: state.enemyBar - action.payload,
                    hpBar: state.hpBar - action.payload2,
                    wepMessage: "Successful!"


                }
            }
            else {
                //console.log("miss")
                return {
                    ...state,
                    wepMessage: "Failed!"
                }

            }


        case 'HP_DOWN2':
            rand = Math.floor((Math.random() * 100) + 1)

            if (state.enemyBar <= -0) {
                console.log('You beat the enemy');
                return {
                    ...state,
                    enemyBar: 0

                }

            }

            else if (state.hpBar <= -0) {
                console.log('You lose!')
                return {
                    ...state,
                    hpBar: 0
                }
            }

            if (rand <= 30) {
                console.log("hit")
                return {
                    ...state,
                    enemyBar: state.enemyBar - action.payload,
                    hpBar: state.hpBar - action.payload2,
                    wepMessage: "Successful!"


                }
            }
            else {
                console.log("miss")
                return {
                    ...state,
                    wepMessage: "Failed!"
                }

            }

        case 'HP_DOWN3':
            rand = Math.floor((Math.random() * 100) + 1)

            if (state.enemyBar <= -0) {
                console.log('You beat the enemy');
                return {
                    ...state,
                    enemyBar: 0

                }

            }

            else if (state.hpBar <= -0) {
                console.log('You lose!')
                return {
                    ...state,
                    hpBar: 0
                }
            }

            if (rand >= 50) {
                console.log("hit")
                return {
                    ...state,
                    enemyBar: state.enemyBar - action.payload,
                    hpBar: state.hpBar - action.payload2,
                    wepMessage: "Successful!"


                }
            }
            else {
                console.log("miss")
                return {
                    ...state,
                    wepMessage: "Failed!"
                }

            }


    }


    return newState;
};

export default reducer;

Капитан. js

export class CaptainScreen extends Component {

    render() {

        return (

            <View style={styles.container}>

                <Text style={styles.title}>Captain Screen</Text>

                <View style={styles.container2} >
                    <Progress.Bar progress={this.props.hpBar} width={200} animated={true} borderColor={'black'} />
                    <Text style={styles.text}>Your HP: {(this.props.hpBar * 100).toFixed(0)}%</Text>
                    <Progress.Bar progress={this.props.enemyBar} width={200} color={'red'} animated={true} borderColor={'black'} />
                    <Text style={styles.text}>Enemy HP: {(this.props.enemyBar * 100).toFixed(0)}%</Text>
                </View>

            </View>



        )

    }
}

const mapStateToProps = (state) => {
    //console.log(state);
    return {
        hpBar: state.hpBar,
        enemyBar: state.enemyBar
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        onEngineer: () => dispatch({ type: 'HP_UP', payload: 0.1 }),
        onWeapon: () => dispatch({ type: 'HP_DOWN', payload: 0.1 })


    }
}

const ConnectedCaptain = connect(mapStateToProps, mapDispatchToProps)(CaptainScreen);

export default Root = () => {
    return (<ConnectedCaptain />)
}

Инженер. js

export class EngineersScreen extends Component {


    render() {
       // console.log("Ship Hp - Engineer Screen: " + this.props.hpBar);

        return (
            <View style={styles.container}>
                <Text style={styles.title}>Engineer Screen</Text>

                <View style={styles.container2} >

                    <Progress.Bar progress={this.props.hpBar} width={200} animated={true} borderColor={'black'} />
                    <Text style={styles.text}>Your HP: {(this.props.hpBar * 100).toFixed(0)}%</Text>

                    <Button title="Quick Fix" onPress={this.props.onEngineer}> </Button>
                    <Button title="Medium Fix" onPress={this.props.onEngineerTwo}> </Button>
                    <Button title="Indepth Fix" onPress={this.props.onEngineerThree} > </Button>

                    <Text>Status of Repair: {this.props.engMessage}</Text>
                </View>
            </View>
        )
    }
}

const mapStateToProps = (state) => {
   // console.log(state);
    return {
        hpBar: state.hpBar,
        enemyBar: state.enemyBar,
        engMessage: state.engMessage,

    }
}

const mapDispatchToProps = (dispatch) => {
    return {


        onEngineer: () => dispatch({ type: 'HP_UP', payload: 0.1 }),
        onEngineerTwo: () => dispatch({ type: 'HP_UP2', payload: 0.2 }),
        onEngineerThree: () => dispatch({ type: 'HP_UP3', payload: 0.3 })


    }
}

const ConnectedEngineer = connect(mapStateToProps, mapDispatchToProps)(EngineersScreen);

export default Root = () => {
    return (<ConnectedEngineer />)
}

Оружие. js

export class WeaponsScreen extends React.Component {

    onChooseColor() {
        this.props.navigation.navigate('PreGame');
    }

    render() {


        console.log(this.props.hpBar)
        if (this.props.enemyBar <= -0) {
            //alert('You Lose');
            this.onChooseColor()
        }

        return (
            <View style={styles.container}>
                <Text style={styles.title}>Weapons Screen</Text>

                <View style={styles.container2} >

                    <Progress.Bar progress={this.props.enemyBar} width={200} color={'red'} animated={true} borderColor={'black'} />
                    <Text style={styles.text}>Enemy HP: {(this.props.enemyBar * 100).toFixed(0)}%</Text>

                    <View style={styles.buttonStyle}>
                        <View>
                            <Button title="Weapon 1" onPress={this.props.onWeapon}> </Button>

                        </View>

                        <View style={styles.buttonStyle}>
                            <Button title="Weapon 2" onPress={this.props.onWeaponTwo}> </Button>

                        </View>

                        <View style={styles.buttonStyle}>

                            <Button title="Weapon 3" onPress={this.props.onWeaponThree}> </Button>

                        </View>

                    </View>

                    <Text>Status of Attack: {this.props.wepMessage}</Text>

                </View>
            </View>
        )

    }


}



const mapStateToProps = (state) => {
    //console.log(state);
    return {
        hpBar: state.hpBar,
        enemyBar: state.enemyBar,
        wepMessage: state.wepMessage,

    }
}

// payload - Your ship dealing damage to enemy
// payload2 - Enemy ship dealing damage to your ship
const mapDispatchToProps = (dispatch) => {
    return {

        onWeapon: () => dispatch({ type: 'HP_DOWN', payload: 0.05, payload2: 0.1 }),
        onWeaponTwo: () => dispatch({ type: 'HP_DOWN2', payload: 0.15, payload2: 0.2, }),
        onWeaponThree: () => dispatch({ type: 'HP_DOWN3', payload: 0.2, payload2: 0.3, }),

    }
}

const ConnectedWeapons = connect(mapStateToProps, mapDispatchToProps)(WeaponsScreen);

export default Root = () => {
    return (<ConnectedWeapons />)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...