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

时间:2018-11-05 15:03:34

标签: javascript api react-native fetch state

因此,我有一个方法,可以获取一个api,从其表ID中获取最大值,然后将该值提供给全局变量。

但是componentDidMount稍后会进行获取,因此我的应用程序会说“未定义”,而不是先获取然后将值分配给变量。

代码:

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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

只需将其添加到global范围内。 例如:global.myVar = "my global variable"