PureComponent浅比较在判断Object和Array等引用类型时会出错
- 在state结构不复杂的项目中:使用
Object.assign
或deepClone
生成一个新的Object
- 在state结构很复杂的项目中
immutable.js
import { fromJS } from 'immutable';
const data = { val: 1, desc: { text: 'a', }, content: { title: 'ha' } }
const a = fromJS(data);
const b = a.set('val', 2); console.log(a.get('val')); console.log(b.get('val'));
const c = a.setIn(['desc', 'text'], 'b'); console.log(a.get('desc') === c.get('desc')); console.log(a.get('content') === c.get('content'));
const aa = toJS(a); const cc = toJS(c); console.log(aa.content === cc.content);
|
import { Map } from 'immutable'; import { cloneDeep } from 'lodash';
getInitialState() { return { data: Map({ times: 0 }), } }, handleAdd() {
this.setState({ data: this.state.data.update('times', v => v + 1) });
this.setState(({data}) => ({ data: data.update('times', v => v + 1) })); }
|
import {is} from 'immutable';
shouldComponentUpdate(nextProps, nextState) { const thisProps = this.props || {}; const thisState = this.state || {}; nextState = nextState || {}; nextProps = nextProps || {};
if (Object.keys(thisProps).length !== Object.keys(nextProps).length || Object.keys(thisState).length !== Object.keys(nextState).length) { return true; }
for (const key in nextProps) { if (!is(thisProps[key], nextProps[key])) { return true; } }
for (const key in nextState) { if (!is(thisState[key], nextState[key])) { return true; } } return false; }
|
immer.js
[TODO]原理
import produce from 'immer';
this.setState( produce(draft => { draft.user.age += 1 }) )
this.state.draft.user.age++;
|