1.create-react-app 脚手架
npm install -g create-react-app
create-react-app myapp
cd myapp
npm start
2.引入sass
npm install sass-loader node-sass --save-dev
- 打开react的webpack配置 (node_modules/react-scripts/config/webpack.config.js)
//找到module下的rules,然后找到最后一个配置,修改成如下的样子
{
loader: require.resolve('file-loader'),
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/,/\.scss$/], 变化位置
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
//同级增加一个scss配置
{
test:/\.scss$/,
loaders:['style-loader','css-loader','sass-loader']
}
3.让react项目支持"decorators"装饰器语法
npm install --save-dev @babel/plugin-proposal-decorators
npm run eject
释放配置文件
释放报错时解决方案
git add .
git commit -m "message"
修改package.json文件
"babel": {
"presets": [
"react-app"
],
//新增
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
//或者配置.babelrc文件
{
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
]
}
//或者
{
//将es6语法转化为es5
test: /\.(m?js|jsx)$/,
//排除的文件夹
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [
'@babel/plugin-transform-react-jsx',
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
]
]
}
}
}
使用装饰器 (高阶组件)
import React,{PureComponent} from 'react';
import {withRouter} from 'react-router-dom'
@withRouter
class TestComponent extends PureComponent{
goAbout=()=>{
this.props.history.push('/about')
}
render(){
return (
<div>
<h3>组件</h3>
<button onClick={this.goAbout}>组件中跳转页面</button>
</div>
)
}
}
// export default withRouter(TestComponent) 没引入装饰器插件时
export default TestComponent
4.css modules 配置
- 如果是
react-create-app
创建的项目
webpack.config.js中修改 新增一个参数modules:true就可以了
//getStyleLoaders 将调用这个函数的地方全部设置 modules:true
//css scss 等都开启模块化
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
})
}
使用css models
:global
全局变量前都加:global
:local
局部变量 默认都是局部变量
//index.scss
.title{
color:red;
}
//局部变量
:local .list{
font-size:18px;
}
//全局变量
:global .title{
color:green;
}
import styles from './index.scss'
render(){
return (
//使用局部变量
<h1 className={styles.title}>list页面</h1>
// 使用全局变量
<h1 className="title">list页面</h1>
)
}
4.css modules 配置
如果是react-create-app创建的项目
webpack.config.js中修改 新增一个参数modules:true就可以了
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
})
}
组件之间传值
- 父-子:props
- 子-父:通过注册事件 带参数
- redux 传递
虚拟dom
js对象结构、插入到文档中、当数据有变化时重新生成新的js对象树、 新旧js对象树进行比较,
将差异更新到第一个js对象树、渲染
- 虚拟dom相当于js和dom之间加了一层缓存,通过diff算法减少对真实dom的操作,提高性能
diff算法
把树形结构按照层级分解,只比较同级元素。
给列表结构的每个单元添加唯一的key属性,方便比较。
React 只会匹配相同 class 的 component(这里面的class指的是组件的名字)
合并操作,调用 component 的 setState 方法的时候, React 将其标记为 dirty.到每一个事件循环结束, React 检查所有标记 dirty 的 component 重新绘制.
选择性子树渲染。开发人员可以重写shouldComponentUpdate提高diff的性能。
React数据获取为什么一定要在componentDidMount里面调用?
- 不建议在
constructor
和componentWillMount
里写的原因是- 会阻碍组件的实例化,阻碍组件的渲染
- 如果用
setState
,在componentWillMount
里面触发setState
不会重新渲染 - 在React Redux中,由于触发的渲染方式不同,是可以不需透过React组件的生命周期方法,
- 你不能保证在组件挂载之前 Ajax 请求已经完成,如果是这样,也就意味着你将尝试在一个未挂载的组件上调用 setState,这将不起作用。在 componentDidMount 中发起网络请求将保证这有一个组件可以更新了。
- 在componentDidMount中请求
- 可以保证数据的加载
(在构造函数中)调用 super(props) 的目的是什么
在 super()
被调用之前,子类是不能使用this
的,在 ES2015 中,子类必须在 constructor 中调用 super()。传递 props 给 super() 的原因则是便于(在子类中)能在 constructor 访问 this.props。
代码分隔、分包加载
lazy
Suspense
如果在 MyComponent 渲染完成后,包含 OtherComponent 的模块还没有被加载完成,我们可以使用加载指示器为此组件做优雅降级。这里我们使用 Suspense 组件来解决。
React.lazy 和 Suspense 技术还不支持服务端渲染
服务端渲染推荐 Loadable Components 这个库
import {lazy} from 'react'
const OtherComponent =lazy(() => import('./OtherComponent'));
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
Fragment
不会向 DOM 添加额外节点 类似vue的template
<Fragment>
<ChildA />
<ChildB />
</Fragment>
性能优化
shouldComponentUpdate
state和props有数据或者对象值的时候 可以考虑JSON.stringify()转化为字符串进行比较
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
if (JSON.stringify(nextState.statusData) !== JSON.stringify(this.state.statusData)) {
return true;
}
return false;
}
PureComponent
使用React.PureComponent
来代替手写 shouldComponentUpdate 但它只进行浅比较,所以当 props 或者 state 某种程度是可变的话,浅比较会有遗漏,那你就不能使用它了。当数据结构很复杂时,情况会变得麻烦
class A extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
words:['test']
};
}
handleClick() {
let words=this.state.words;
words.push('marklar')
this.setState(state => ({
words: words
}));
};
//解决办法 使用es6或者 其他将words的this内存指针改变
//state.words.concat(['marklar'])
//对象的时候推荐如下或者es6解构
// Object.assign({}, colormap, {right: 'blue'});
handleClick() {
this.setState(state => ({
words: [...state.words, 'marklar'],
}));
};
}
PropTypes类型检查
import PropTypes from 'prop-types';
class A extends Component{
//设置默认值
static defaultProps = {
Num: 2
}
//类型检测
static propTypes = {
Num: PropTypes.number,
ids: PropTypes.string
}
}
//或者
A.defaultProps = {
Num: '2'
}
A.propTypes = {
Num: PropTypes.number,
ids: PropTypes.string
};