请我的 react 类有这个问题,我正在尝试更新我的状态,但我收到了这个错误“无法读取未定义的属性'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>
)
}
}
最佳答案
function () { ... }
语法不会维护上下文中的 this
引用。改用箭头函数:
then(() => {
this.setState({lat: objec.latitude, longi: objec.longitude})
})
另一种选择是在 function () { }
之后添加 .bind(this)
。
或者,只需将 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)
然而,箭头函数正是针对这类问题引入的。
关于reactjs - 'this.setState' 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46788299/