方法一:在安装好nodejs的情况下
npm install -g create-react-app 全局安装react脚手架
create-react-app 项目名 创建一个新的react项目
方法二:直接安装
npx create-react-app 项目名
npx create-react-app 项目名 --template typescript
注意:创建好的项目配置文件webpack相关是隐藏的,需要运行npm run eject解包展示出来。但是是不可逆的,所以可以换以下方式!
# 解包前必须做git提交,到commit就行了,否则无法解包(这是为了方便随时做版本回滚)
$ git add .
$ git commit -m '解包前'
$ npm run eject# 会发现多了个config配置文件夹。
# 项目默认配置了sass ,但是想要使用less需要找到sassModuleRegex重新配置一下
{test: /\.less$/,use: getStyleLoaders({//暂不配置},'less-loader'),
},
useState 便于修改变量
useEffect 模拟三个生命周期:mounted(componentDidMount)updated(componentDidUpate)beforeDestory(componentWillUnmount)
useRef 用于获取节点
createContext 方便多级组件传参
旧版生命周期(react17之前)
初始阶段 设置 props and state(static设置属性和constructor设置状态)
挂载阶段 componentWillMount render componentDidMount
修改阶段 修改 props and states ==> props: componentsWillReceiveProps -- shouldComponentUpdate -- componentWillUpdate -- render -- componentDidUpatestates: shouldComponentUpdate -- componentWillUpdate -- render -- componentDidUpate
销毁阶段 componentWillUnmount
新版生命周期(react17及之后) --will的的都没有了
创建阶段
修改阶段
销毁阶段
没有索引key:一一对比。老的节点与新的节点比。依次对比。
有索引key优化 :先比较索引key,再比较元素类型(元素类型相同的都可以复用),再比较函数内容,再比较下标,新下标<=老下标则不需要更新。新下标>老下标则需要移动和更新。其他索引key不同的,直接进行新增和删除。例子如下:
class AAA extends React.Component {constructor(props) {super(props) //相当于this.props=props重写父类构造函数this.state ={visible:true}; //设置默认状态}handleClick=()=>{this.setState({visible:!this.state.visible})}render() {//4的时候没有子组件,componentWillUnmount卸载子组件return ( {this.state.visible?- A
- B
- C
- D
- E
- F
: - A
- C
- E
- B
- G
})}
}
观察控制台元素发现,点击按钮,元素改变。有些元素不重新渲染有些元素重新渲染
原理:先比较key是否相同,相同比较type元素类型。再比较内容,内容相同,比较下标(0到n)。如果新下标<=老下标,那么是绿色的,不用更新。如果新下标>老下标,那么是黄色的,需要移动和更新。如果新的没有此元素或者老的多余了,进行新增和删除

小项目可以用context,大项目还是用redux