简体   繁体   English

React Native-如何从我的提取方法中使变量成为全局变量

[英]React Native - How to make a variable global from my fetch method

So I have a method where I fetch an api, get the highest value from it's tables ID and then give that value to a global variable. 因此,我有一种方法,可以获取一个api,从其表ID中获取最大值,然后将该值提供给全局变量。

However componentDidMount does the fetching later, so my app says 'undefined' instead of fetching first and then assigning the value to the variable. 但是componentDidMount稍后会进行获取,因此我的应用程序会说“未定义”,而不是先获取然后将值分配给变量。

Code: 码:

constructor(props) {
    super(props);
    this.state = {
        data: [],
        id: '',
    };
}



fetchData = () => {
            fetch(url)
                .then(request => request.json())
                .then(response => {
                    this.setState({
                        data: response,
                        id:Math.max.apply(Math, response.map(function (o) { return o.id; })) + 1,
                    });
console.log(this.state.id) // this gives me the highest id + 1 /here it works but check the render method!
                });
        }


componentDidMount = () => {
            this.fetchData();
        }


render() {
    return (
        <View
            style={styles.container}
        >
            <ScrollView>
                <TextInput
                    style={styles.input}
                    placeholder={this.state.id} //here it uses the original states value which is empty ('') and not the one from the fetch' setState...why?
                    onChangeText={(text) => this.updateValue(text, 'id')}
                />

            </ScrollView>

        </View>
    );
  }
}

Just add it to global scope. 只需将其添加到global范围即可。 ex: global.myVar = "my global variable" 例如: global.myVar = "my global variable"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM