React Native - Как сделать переменную глобальной из моего метода fetch - PullRequest
0 голосов
/ 05 ноября 2018

Итак, у меня есть метод, в котором я получаю API, получаю наибольшее значение из его идентификатора таблицы, а затем передаю это значение глобальной переменной.

Однако componentDidMount выполняет выборку позже, поэтому мое приложение говорит «undefined» вместо выборки сначала, а затем присваивает значение переменной.

Код:

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 голосов
/ 05 ноября 2018

Просто добавьте его в область действия global. например: global.myVar = "my global variable"

...