【发布时间】:2026-01-03 01:55:02
【问题描述】:
所以我有一个方法可以获取一个 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>
);
}
}
【问题讨论】:
-
如果渲染没有得到更新的值,看起来 fetch 调用不起作用??
-
能不能在返回前console.log(this.state)?
-
不要把它放在全局中,你可以很容易地让它在状态下工作。我们只需要更多信息,关于什么是响应以及渲染后的状态是什么。同样在这里你得到未定义,因为 global.id 在你填充它之前不存在。
-
这是在安卓里吗?
-
我知道这是 react-native,我的意思是 android textinput 占位符,如果我记得不要重新渲染,你能用 value 试试看是否有效吗?
标签: javascript api react-native fetch state