本文目录
一、react中使用antd组件库
运行命令create-react-app antd-react
创建新项目:
运行命令npm i antd
安装:
使用:
import React from 'react'
import ReactDOM from 'react-dom'
import 'antd/dist/antd.css';
import { Button } from 'antd';
ReactDOM.render(
<div>
<Button type="primary">Primary Button</Button>
</div>,
document.getElementById("root"));
二、Immutable
每次修改一个immutable对象时都会创建一个新的不可变的对象,在新对象上操作并不会影响到原对象的数据。
2.1 深拷贝和浅拷贝的关系
2.2 immutable优化性能方式
安装输入命令npm i immutable
:
2.3 immutable的Map使用
map
使用(map只能套一层,如果属性还是对象或者数组的话就再套一层):
import React from 'react'
import { createRoot } from 'react-dom/client';
import 'antd/dist/antd.css'
import { Button } from 'antd'
import {Map} from 'immutable'
var obj = {
name: 'immutable'
}
var oldObj = Map(obj)
console.log(oldObj)
// 更改值
var newObj = oldObj.set('name', 'react')
// 1.获取值:get获取
console.log(oldObj.get('name'), newObj.get('name'))
// 2.获取值:普通对象
console.log(oldObj.toJS(), newObj.toJS())
const container = document.getElementById('root')
const root = createRoot(container)
root.render(
<div>
<Button type="primary">Primary Button</Button>
</div>
)
效果:
state
中使用:
import React, { Component } from 'react'
import { Map } from 'immutable'
export default class imMap extends Component {
state = {
info: Map({
name: 'immutable',
key: 100
})
}
render() {
return (
<div>
<button onClick={() => {
this.setState({
info: this.state.info.set('name', 'react').set('key', 101)
})
}}>onclick</button>
{this.state.info.get('name')} --
{this.state.info.get('key')}
</div>
)
}
}
可以看到多个值时,immutable可以链式操作。
2.4 immutable的List使用
import React, { Component } from 'react'
import {List} from 'immutable'
var arr = List([1,2,3])
var arr1 = arr.push(4)
var arr2 = arr1.concat([5])
console.log(arr.toJS(), arr1.toJS(), arr2.toJS())
export default class ImList extends Component {
render() {
return (
<div>ImList</div>
)
}
}
效果:
2.5 实际场景formJS
在实际开发中我们的state中数据结构一般来自后端返回的,那么我们将使用formJS
:
import React, { Component } from 'react'
import { fromJS } from 'immutable'
export default class ImFromJs extends Component {
state = {
info: fromJS({
list: ['1', '2', '3'],
obj: {
name: 'immutable',
key: 100,
}
})
}
render() {
return (
<div>ImFromJs
<div><button onClick={() => {
this.setState({
info: this.state.info.setIn(['obj', 'name'], 'react')
})
}}>改变标题</button></div>
<div><button onClick={() => {
this.setState({
info: this.state.info.updateIn(['list'], (oldList) => {
return oldList.push(oldList._tail.array.length + 1)
})
})
}}>改变数组</button></div>
<div>{this.state.info.getIn(['obj', 'name'])}</div>
<div>
<ul>
{
this.state.info.get('list').map((item, index) => {
return <li key={index}>{item}
<button onClick={() => {
this.setState({
info: this.state.info.updateIn(['list'], (oldList) => {
return oldList.splice(index, 1)
})
})
}}>del</button>
</li>
})
}
</ul>
</div>
</div>
)
}
}
效果:
三、redux中使用immutable