React 基础知识
1 首先创建一个新项目
- 创建项目: npx create-react-app my-app
- 打开项目: cd my-app
- 启动项目: npm start
2.基本使用
React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面
下面是简单的定义数据,渲染
map不能遍历array数组,只能遍历object对象。所以如果遇到这样的问题可以采用forEach试一下
记住要有唯一的key值
import React, { Component } from 'react'
export class Index extends Component {
state={ //state 定义数据
data:[
{id:1,name:'阿达',age:18,sex:'qwe'},
{id:2,name:'艾斯',age:18,sex:'qwe'},
{id:3,name:'路飞',age:18,sex:'qwe'},
{id:4,name:'萨博',age:18,sex:'qwe'}
]
}
render() {
return (
<div>
{
this.state.data.map((v,i)=>{ //map 循环
return <ul key={v.id}>
<li>{v.id}</li>
<li>{v.name}</li>
<li>{v.age}</li>
</ul>
})
}
</div>
)
}
}
export default Index
组件
组件,从概念上类似于 JavaScript 函数。它接受的参数(就是 “props”),并返回用于描述页面展示内容的 React 元素。 组件有两种形式:class组件和function 函数组件。
class类组件
class组件拥有状态和生命周期,继承Component,实现render方法。
下载此插件,新建页面后输入rce 会自动提示出下图代码 为class类组件
下图是function 函数组件。下载插件后rfce提示
函数组件无状态,只有关注的内容会展示,返回渲染结果
关于setState()
我们都知道,React是通过this.state来访问state,通过this.setState方法更新state。当this.setState的方法被调,React会重新调用render方法来重新渲染
setState正确使用
this.setState({datas: 'Hello'});
接下来是React的生命周期
- 组件将要挂载时:componentWillMount
componentWillMount(){
console.log('即将挂载')
}
- 组件挂载完成时:componentDidMount
componentDidCatch(){
console.log('挂载完成');
}
// 实例期
// getDefaultProps
// getInitialState
// componentWilMount
// {render}
// componentDidCatch
- 是否要更新数据时:shouldComponentUpdate
- 将要更新数据时:componentWillUpdate
- 数据更新完成时:componentDidUpdate
- 组件将要销毁时:componentWillUnmount
- 父组件中改变了props传值时:componentWillReceiveProps