因此,我有一个方法,可以获取一个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>
);
}
}
答案 0 :(得分:0)
只需将其添加到global
范围内。
例如:global.myVar = "my global variable"