then方法中this指向问题

来源:2-3 Ajax获取Header组件数据

weixin_慕码人9177259

2020-04-05 11:37:54

import React ,{Component,Fragment} from 'react';

import ReactDOM from 'react-dom';

import logo from './logo.png';

import {Menu} from 'antd';//导入横向菜单组件

import "./style.css"//导入css样式表

import axios from 'axios';

class AppHeader extends Component{

constructor(props){

super(props);

this.state={

list:[]

    }

}

getMenuItem(){

    return  this.state.list.map(item=>{

   return  <Menu.Item key={item.id}> 

           {item.title}

           </Menu.Item>

})

}

render(){

return(

<Fragment>

<img src={logo} className="app-header-img"/ >

<Menu className="app-header-menu" mode="horizontal">

{this.getMenuItem()}

</Menu>

</Fragment>

)

}

componentDidMount(){

 

axios.get('http://www.dell-lee.com/react/api/header.json')

.then(

(res)=>{console.log(this)

// console.log(res.data.data);

// this.setState

})

}

}

export default AppHeader;


 componentDidMount(){

   不太懂以下代码中this的指向问题,一般箭头函数没有this,里面的this是从父级作用域中获取来的,这里的父级作用域是不是then()方法的作用域,那是什么呢then方法中this是指向谁呢?请大神指点

axios.get('http://www.dell-lee.com/react/api/header.json')

.then(

(res)=>{console.log(this)

// console.log(res.data.data);

// this.setState

})

}


写回答

1回答

好帮手慕星星

2020-04-06

同学你好,this指向的当前AppHeader组件。then方法在componentDidMount()方法中,而这个方法在当前组件中,所以this指向的当前组件,自己可以输出看看

http://img.mukewang.com/climg/5e8add5e095ed2b811700363.jpghttp://img.mukewang.com/climg/5e8add6409baa0c411110031.jpg

祝学习愉快!

0

0 学习 · 10739 问题

查看课程