react 异步组件传值

1,886 阅读1分钟

react 类组件,父组件通过 axios 异步获取数据 , 获取成功之后通过 props传递给子组件, 子组件通过 state 单独管理内部数据.

类组件

Child写法:

class Roles extends React.Component<IProps, IState> {
  state = {
    value: this.props.roleIds,
    roleList: this.props.roleList,
  };

  componentDidMount() {
    console.log(this.state.roleList)  // []
  }

  render() {}
}

Parent写法

<!-- roleList为异步获取的数据 -->
<Child 
    workId={workId} 
    logId={log.id} 
    roleIds={log.roleIds} 
    roleList={roleList} />

问题

image.png

父组件值改变但是子组件state值不变

原因

react 生命周期图片

image.png

子组件的代码,在构造函数内初始化了自己全新的state,数据是当前组件props传入的数据 (对于本例来说, 就是父组件初始化 roleList的数据 [ ]),在render函数内通过this.state取数据,这样当父组件调用setState重新赋值数据之后,而子组件state里面的数据并没有发生变化,所以子组件不会重新render页面

解决 1: 通过 key值

react中的key属性,它是一个特殊的属性, 是帮助 React 识别哪些元素改变了, key值改变, react组件会进行销毁重建

一个元素的 key 最好是这个元素在列表中拥有的一个独一无二的字符串, 兄弟元素 key 唯一, 没有合适作为key可以 Math.random() 或 new Date().getTime() 生成

修改 1

<Child 
    workId={workId} 
    logId={log.id} 
    roleIds={log.roleIds} 
    roleList={roleList} 
    key={new Date().getTime()} />

image.png