react-lifecycle

Html code posted by xialvjun
created at 12 Jul 11:53

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<Lifecycle
  props={{ list }}
  getDerivedStateFromProps={(props, state) => {
    const plist = props.list,
          slist = state.list;
    if (plist.length > slist.length) {
      return {
        list: plist.map(pit => 
          slist.findIndex(sit => sit.id===pit.id) > -1 ?
            pit :
            { ...pit, just_insert: true }
        )
      }
    }
    if (plist.length < slist.length) {
      return {
        list: slist.map(sit =>
          slist.find(pit => sit.id===pit.id) ||
          { ...sit, just_remove: true }
        )
      }
    }
    return props;
  }}
  componentDidUpdate={(prevProps, prevState, snapshot, instance) => {
    setTimeout(() => {
      instance.setState(state => ({ list: state.list.filter(it => !it.just_insert && !it.just_remove) }));
    }, 300);
  }}
>
  {state => state.list.map(it => (
    <div key={it.id} className={`${it.just_insert ? 'inserting' : ''} ${it.just_remove ? 'removing' : ''}`}>
      content
    </div>
  ))}
</Lifecycle>
1 KB in 2 ms with coderay