React-native 0.35 setState问题

时间:2016-10-16 16:03:37

标签: reactjs react-native

无法从数据库更新状态。 console.log(db_name)返回数据。但无法在render / state / global.var上访问它。 如何对访问局部变量做出反应,以便可以在render jsx中使用它。

import React, { Component } from 'react';

import { AppRegistry, Text, View } from 'react-native';

import axios from 'axios';

class Easycall extends Component {

constructor(props) {

 super(props);

 this.state = {name:"name",};

}

gettt(){

  axios.get('http://192.168.43.236/dbzx.php')

  .then(function (response) {

  let db_name = response.data.name ;

  this.setState({name:db_name});

});

}


render() {

  this.gettt();

  return (<Text>{this.state.name}</Text>);

  }


}


 AppRegistry.registerComponent('Easycall', () => Easycall);

3 个答案:

答案 0 :(得分:1)

尝试改变:

gettt(){

  axios.get('http://192.168.43.236/dbzx.php')

  .then(function (response) {

  let db_name = response.data.name ;

  this.setState = ({name:db_name});

});

} 

为:

gettt(){

  axios.get('http://192.168.43.236/dbzx.php')

  .then((response) => {

  let db_name = response.data.name ;

  this.setState = ({name:db_name});

});

}

答案 1 :(得分:0)

import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';
import axios from 'axios';

class Easycall extends Component {

    constructor(props) {
        super(props);
        this.state = {name:"name"};
    }

    componentWillMount(){
        this.gett();
    }

    gettt(){
        axios.get('http://192.168.43.236/dbzx.php')
        .then(function (response) {
            let db_name = response.data.name ;
            this.setState({name:db_name});
        });
    }

    render() {
        return (<Text>{this.state.name}</Text>);
    }

}

AppRegistry.registerComponent('Easycall', () => Easycall);

答案 2 :(得分:0)

您需要绑定需要访问Team Explorer -> Changes -> ...(Options) -> Compare File as Default Action.的方法。

避免在渲染函数中调用setState()。而是在上面的类中添加以下生命周期方法:

this

您现在可以在gettt()中执行 this .setState()。