导语
componentWillReceiveProps
虽已退隐江湖,但大哥的事迹还在江湖中流传。
通常用它对props
转换为对应的state
,虽然记忆函数+render可以代替一些场景。
大哥在挂载阶段不执行,相信不少人被constructor
执行setState
无效坑过。
而且一大段关系不大的代码写在一起也很头疼,前面还要包裹if
,即便你所依赖的属性没变化大哥也要出场...
跟大哥告别吧!时代变了!
正文

当用户点击设置会弹出模态框,可以对属性进行更改

在App.tsx
中用ref
的方式使得模态框显示
private addModalRef = React.createRef<AddModal>();
<AddModal ref={this.addModalRef}></AddModal>
点击设置按钮调用
private onSettingUpdate = (record: IHero) => {
this.addModalRef.current?.showModal(record);
};
IHero
定义如下:
export interface IHero {
id: string;
name: string;
age: number;
}
在AddModal
中
public showModal = (hero: IHero) => {
this.setState({
hero,
visible: true,
});
};
相比于
<AddModal visible={visible} hero={hero} onHandle={this.onHandle}></AddModal>
或者
{visible && <AddModal hero={hero} onHandle={this.onHandle}></AddModal>}
要优雅很多,AddModal
的功能更内聚了,完成功能也不用 先触发父组件的render
一次,大家都少了些模板代码。
如果是功能复杂的模块,可以对外提供多个方法,使得关系明确化,相比扎推在componentWillReceiveProps
中,逻辑清晰多了。
不足的是ref
的穿透问题,因为ref
和 key
一样由React
自己维护,不能穿透。
对于connect
,F12进去
<TStateProps = {}, no_dispatch = {}, TOwnProps = {}, State = DefaultRootState>(
mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
mapDispatchToProps: null | undefined,
mergeProps: null | undefined,
options: Options<State, TStateProps, TOwnProps>
): InferableComponentEnhancerWithProps<DispatchProp & TStateProps, TOwnProps>;


网友评论