reactjs - 'this.setState' 有什么问题

标签 reactjs

请我的 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/

相关文章:

node.js - React Native/Node API : Can't set headers after they are sent

javascript - 如何使用 React 在客户端向外部站点发出 AJAX GET 请求

javascript - 如何在 React Admin 包中显示来自服务器端验证的自定义错误消息?

reactjs - 无法在未安装的组件上执行 useCallback 的 React 状态更新

css - ReactJS Material UI - 设置 TextField 的悬停边框颜色的问题

javascript - React useEffect 清理函数运行多次?

css - React-Native:带百分比值的边距

javascript - 我需要使用什么生命周期 Hook ? - react

javascript - 减少不删除正确的数组项

javascript - React.js 使用 javascript 更改输入值