我有一个文本输入,它是空的,直到用户改变了它的值,然后状态才会改变。React本机的问题是,无论状态上是否存在值,它都将继续呈现。到目前为止这是我的密码。
第一部分通常用于设置状态的反应本机代码。
export default class Whereto extends Component<{}> {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
location: null,
error: null,
markers:[],
goingto: '',
};
}代码的第二节是componentWillMount部分,据我所知,它是用来在呈现之前更新状态的,下面是我的尝试:
componentWillMount(){
navigator.geolocation.getCurrentPosition(
(pos) => {
this.setState({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
error: null,
});
//directions api
var apiDirectionskey = '';
const {goingto} = this.state;
fetch('https://maps.googleapis.com/maps/api/directions/json?origin=' + pos.coords.latitude + ',' + pos.coords.longitude + '&destination=' + goingto + '&mode=transit&arrival_time=1391374800&key=' + apiDirectionskey)
.then((resdirections) => resdirections.json())
.then((responseJson3) => {
// noinspection JSAnnotator
if (goingto !== '') {
console.log(responseJson3);
} else {
console.log('no-response');
}
});第三节是我的呈现部分,它有文本输入呈现(){
return(
<View style={styles.container}>
<Mainlogo/>
<TextInput style={styles.boxInput} underlineColorAndroid='rgba(0,0,0,0)' placeholder="Going To?"
underlineColorAndroid='transparent'
onChange={(dest) =>this.setState({goingto : dest})}
/>..。从大得多的代码中截断。)
}
}我没有包含一个按钮,只是一个改变状态的文本框,称为goingto。我已经修改了几个小时的代码,仍然无法从获取调用中获得响应或结果,因为我需要将goingto状态的值作为一个参数来完成提取调用。它仍然是空的,或者至少在输入更改TextInput之后,我认为它是空的。任何关于如何正确地做这件事的指示都是很棒的。
console.log()是由set状态产生的。
这个结果首先来自我的提取部分。
14:50:46
no-response这个结果来自我的文本输入,只接受单个字符。
Object {
"goingto": "N",
}
14:50:55
Object {
"goingto": "O",
}
14:50:55
Object {
"goingto": "T",
}
14:50:55
Object {
"goingto": "T",
}
14:50:56
Object {
"goingto": "I",发布于 2018-04-19 00:21:57
只有在更新了组件的状态时,组件才会重新启动。在您提供的代码中,只有两个setState:第一个在componentWillMount中,第二个在TextInput中。关键是要识别哪些组件被多次调用,从而导致组件继续呈现。我认为调试它的最好方法是向您的console.log回调中添加一个setState,这样在setState完成后日志将被打印出来。
需要注意的是,componentWillMount是一个同步方法,确保navigator.geolocation.getCurrentPosition不需要是异步的,否则,您的状态总是为空的,因为它没有足够的时间执行。
如果您需要getCurrentPosition是异步的,则不能在componentWillMount上调用它。
如果这有帮助的话请告诉我。
https://stackoverflow.com/questions/49909877
复制相似问题