'this.setState'有什么问题

Joh*_*ere 1 reactjs

请问我的反应类有这个问题,我正在尝试更新我的状态,但我得到这个错误"无法读取属性'setState'的未定义"..我已经尝试过在线的每个解决方案,但没有运气

这是代码

export default class PageBackground extends Component{
    constructor(props) {
            super(props);

            this.state={
                lat         :'nothing',
                longi       :''
            };
            this.getLocation=this.getLocation.bind(this);
            }


        componentWillMount() {
            this.getLocation();
        }
        getLocation () {

            fetch('http://freegeoip.net/json/')
             .then((res)=>res.json())
             .then(function (objec){this.setState({lat:objec.latitude,longi:objec.longitude});})
             .catch((err)=>console.log("didn't connect to App",err))
             console.log(this.state.lat)
        }

        render(){
            return(
                <p>{this.state.lat}</p>
                )
            }
        }
Run Code Online (Sandbox Code Playgroud)

Sul*_*han 6

function () { ... }语法不会维持this从上下文参考.使用箭头功能代替:

then(() => {
    this.setState({lat: objec.latitude, longi: objec.longitude})
})
Run Code Online (Sandbox Code Playgroud)

另一个选择是添加.bind(this)之后function () { }.

或者,只需保存this到局部变量并在函数内使用它:

var self = this;
fetch('http://freegeoip.net/json/')
         .then((res)=>res.json())
         .then(function (objec){self.setState({lat:objec.latitude,longi:objec.longitude});})
         .catch((err)=>console.log("didn't connect to App",err))
         console.log(this.state.lat)
Run Code Online (Sandbox Code Playgroud)

但是,箭头函数是针对这类问题引入的.


归档时间:

查看次数:

374 次

最近记录:

8 年,3 月 前