如何在React Native中渲染之前更改TextInput之后的状态?

时间:2018-04-18 22:22:25

标签: react-native

我有一个文本输入为空,直到用户更改其值,然后才更改状态。 React native的问题在于,无论状态是否有值,它都将继续呈现。到目前为止,这是我的代码。

第一部分用于设置状态的常用反应原生代码

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

...从更大的代码中截断..     )

    }
}

我没有包含按钮,只是一个更改状态的文本框,名为goto。我已经修改了几个小时的代码,仍然无法得到响应或从我的提取调用中得到结果,因为我需要将我的状态值作为参数才能完成我的提取调用。它仍然是空的,或者至少我认为在我输入更改TextInput后它是空的。关于如何正确完成这一任务的任何指示都很棒

console.log()来自设置状态。

此结果首先来自我的获取部分

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",

1 个答案:

答案 0 :(得分:0)

只有在状态更新时,您的组件才会重新呈现。在您提供的代码中,您只有2 setState:首先在componentWillMount中,第二个在TextInput中。关键是要确定哪些被调用多次,这样才能使你的组件继续渲染。 我认为调试它的最佳方法是在setState回调中添加console.log,这样就可以在setState完成后打印日志。

重要的是要提到componentWillMount是同步方法确保navigator.geolocation.getCurrentPosition不需要异步,否则,您的状态可能始终为空,因为它没有& #39; t有足够的时间来执行。

如果您需要getCurrentPosition异步,则不得在componentWillMount上调用它。

如果这有帮助,请告诉我。