1,在学习 Reactjs 的时候遇到以下报错
this.setState is not a function
这个明显是因为 this 指向上下文不对应导致的
2,setState 是 Reactjs 中 components 的默认方法,但是这里的 this 指向不对应
比如以下例子
export default class Header extends React.Component { constructor(props) { super(props) } getContent(){ // 这里的 this 指向 Header,而 Header 继承了 React.Component console.log(this) this.setState({ loading: true }); fetch(url).then(function(response) { // 这里的 this 已经发生变化了 console.log(this) this.setState({ loading: true }); return response.json() }).then(function(data){ // 这里的 this 已经发生变化了 console.log(this) this.setState({data: data}); }) } }
根据 console 打印出来的信息,即可发现 this 在进入 fetch() 函数时已经发生变化了
3,如何解决这个 this 上下文不对应的问题了
网上其实有很多解决方法了
https://www.sitepoint.com/bind-javascripts-this-keyword-react/
Reactjs 自己挖的坑当然也会提供提坑的方法
https://facebook.github.io/react/docs/handling-events.html
以上方法都是为了把 this 绑定到继承 React.Component 的对象 Header 上,使得对象拥有 React.Component 的默认方法 setState()
4,我采用的方法是,通过箭头函数
关于箭头函数,请看之前的介绍
借助箭头函数自动捕获外围对象作为 this 值
export default class Header extends React.Component { constructor(props) { super(props) } getContent(){ // 这里的 this 指向 Header,而 Header 继承了 React.Component console.log(this) this.setState({ loading: true }); fetch(url).then((response) => { // 箭头函数,捕获外围对象的作为 this,即指向 Header console.log(this) this.setState({ loading: true }); return response.json() }).then(function(data){ // 测试,保留 // 这里的 this 已经发生变化了 console.log(this) this.setState({data: data}); }) } }
再次查看日志,就会发现箭头函数自动捕获到 Header 对象
setState 函数报错已经跳到最后一个没有箭头函数的方法 function(data) 里了
5,还有一个问题
箭头函数在ES5编译到ES6时,需要借助 Babel 的特殊转换包,详情查看这里
Leave a Reply