在React Navigation中正确收听“ isFocused”布尔值

时间:2018-08-14 05:49:55

标签: javascript reactjs react-native listener react-navigation

我理解这是一个已经讨论过很多话题,但是作为React作为框架结构 和React Native以及应用开发本身的新手,我对如何做感到很困惑这个。 (我的经验是从Java,C#开始的;然后转到Angular进行实验,现在我正在使用React)

我正在使用React Navigation库;虽然大多数API等都已经明确,但我不确定如何获取和“监听” /“订阅”您可以获取的焦点属性;例如,将焦点放在新焦点上,加载新设置或实际上允许camera元素渲染以停止资源浪费。

我发现了这一点:https://reactnavigation.org/docs/en/with-navigation-focus.html#example,它深入研究了对“ isFocused” prop元素的访问。但是我不知道该怎么做,就是订阅此布尔值的更改,因此当我将Tab键返回到一个元素时,componentDidMount将不会被调用(这是我最初准备Tab标签组件,加载设置等)的方式,现在我无法调用尝试刷新可能已更改的设置(例如,如果用户转到设置并从列表中更改服务器IP,但是该组件已经加载了旧的而未加载新的)。

以下是组件:

import React from 'react';
import { View, Text, AsyncStorage, TouchableHighlight } from 'react-native';
import { createStackNavigator, withNavigationFocus } from 'react-navigation';
import Camera from 'react-native-camera';
import GlobalStyle from '../../assets/styles';
import Network from '../../functions/Network';
import StockScreen from "../Screens/StockScreen";
import Notification from 'react-native-in-app-notification';
import StockObject from "../../objects/StockItem";

class ScannerScreen extends React.Component {

    static navigationOptions = {
        title: 'Scanner',
    };

    constructor(props) {
        super(props);
        this.state = {
            server: null,
            barcodeFound: false,
            isFocused: false,
        }
    }

    componentDidMount() {
        this._loadSettings();
        if(this.props.isFocused) {
            this._loadSettings();
            console.log('screen focused');
        }
    }
    _onFocus = () => {
        if(this.props.isFocused) {
            console.log('focused');
        }
    };

    _loadSettings = () => {
        AsyncStorage.getItem('tgSettings', (err, result) => {
            if(!err) {
                console.log('result before null check ', result);
                if(result !== null) {
                    console.log('result after null check ', result);
                    let settings = JSON.parse(result);
                    this.setState({server: settings.servers[settings.selectedServer].value});
                }else{
                    alert('Please ensure your settings are setup and correct in the settings tab')
                }
            }else{
                alert('set server IP in settings');
            }
        }).then(() => {
            //alert('end of promise for getting storage');
        });
    };

    componentWillUnmount() {
        this.setState({barcodeFound: false});
        //this._sub.remove();
    }

    _onBarCodeRead = (e) => {
        if(!this.state.barcodeFound) {
            this.setState({barcodeFound: true});
            const query = Network.prepareURL({code:e.data},'barcode', this.state.server);
            Network.executeQuery(query).then(res => {
                const {success, data} = res;
                console.log(success, data);
                if (success) {
                    Network.handleResponse(data).then(res => {
                        const {result, data} = res;
                        console.log(result, data);
                        if (result) {
                            console.log(data);
                            let item = new StockObject(data[0]);
                            //let item = data[0];
                            this.props.navigation.navigate('QuickStockScreen', {
                                price: item.Retail,
                                SOH: item.SOH,
                                item: item
                            })
                        }
                    })
                } else {
                    alert('Failed to find any results');
                }

            }).catch(err => {
                alert(err)
            });
            setTimeout(() => {
                this.setState({barcodeFound: false});
            }, 3000);
        }
    };

    render() {
        return (
            <View style={styles.container} keyboardShouldPersistTaps="handled">
                <Notification ref={(ref) => { this.notification = ref; }} />
                <Camera
                    style={styles.preview}
                    onBarCodeRead={this._onBarCodeRead.bind(this)}
                    ref={(cam) => { this.camera = cam; }}
                    aspect={Camera.constants.Aspect.fill}>

                    <View style={{}}>
                        <Text>{this.props.isFocused ? 'Focused' : 'Not focused'}</Text>
                    </View>
                </Camera>

            </View>
        );
    }
}

export default createStackNavigator({
    Scanner: withNavigationFocus(ScannerScreen),
    Stock: StockScreen,
});

const styles = { container: { height: 300, flex: 1 }, preview: { flex: 1 }, buttonStyle: { marginTop: 20, marginLeft: 20, marginRight: 20, marginBottom: 20, alignSelf: 'center' } };

我的目标和目标是解决这个问题的“出发点”;在“ componentDidMount”功能上,我订阅了this.props.isFocused,当它更改时,我调用了相关功能。我真的很困惑如何正确地执行以下操作:https://reactnavigation.org/docs/en/navigation-prop.html#docsNav

所以我确实尝试了几件事;但是主要的问题是我不了解这些示例的工作方式,因此针对我的个人用例对其进行调整一直存在问题。非常感谢您为我提供的任何帮助或见识

0 个答案:

没有答案