版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/well2049/article/details/79430523
React组件挂载时有关的生命周期函数有以下几个:
constructor()
componentWillMount()
render()
componentDidMount()
constructor()
构造函数被调用是在组件准备要挂载的最一开始,此时组件尚未挂载到网页上,一般是在这里设置组件的初始状态this.state({})
和初始的参数数据。
componentWillMount()
函数方法的调用在constructor()
之后,在render()
之前,在这方法里的代码调用setState方法不会触发重渲染,所以它一般不会用来作加载数据之用,它也很少被使用到。
如果在这个函数里面调用setState,本次的render函数可以看到更新后的state,并且只渲染一次。
componentDidMount()
在组件挂载之后调用一次,一般从后台(服务器)获取的数据,都会与组件上要用的数据加载有关,所以都写在componentDidMount()
方法里面执行加载。所以所有有副作用的代码都会集中在componentDidMount方法里。
案例:
class NewTable extends Component {
state = {
selectedRowKeys: [], // Check here to configure the default column
jsonData: []
};
onSelectChange = (selectedRowKeys) => {
console.log('selectedRowKeys changed: ', selectedRowKeys);
this.setState({selectedRowKeys});
}
componentDidMount() {
this.getJsonData();
}
getJsonData = () => {
const _this = this;
axios.get("http://localhost:3100/selfJson/news.json")
.then(function (response) {
let json = response.data.data;
_this.setState({jsonData: json});
console.log(json)
})
.catch(function (error) {
console.log(error);
})
}
render() {}