Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support dynamic form field #100

Closed
afc163 opened this issue Aug 24, 2017 · 7 comments · Fixed by #117
Closed

Support dynamic form field #100

afc163 opened this issue Aug 24, 2017 · 7 comments · Fixed by #117
Assignees

Comments

@afc163
Copy link
Member

afc163 commented Aug 24, 2017

this.state.switch ? getFiledDecorator('xxx')(
  <input />
) : getFiledDecorator('xxx')(
  <select />
)

ant-design/ant-design#7302

@afc163
Copy link
Member Author

afc163 commented Aug 24, 2017

Maybe we can try to resolve this problem elegantly.

@330551887
Copy link

{this.state.visible && <Modal visible={true} />}

@benjycui
Copy link
Member

benjycui commented Nov 1, 2017

这个问题,其实是因为共享同一个 fieldName 的多个组件类型不一样,所以在切换时,react 会先把之前的组件 unmount,然后就触发了这段逻辑

form/src/createBaseForm.js

Lines 308 to 314 in f63c852

if (!component) {
// after destroy, delete data
this.fieldsStore.clearField(name);
delete this.instances[name];
delete this.cachedBind[name];
return;
}

以上逻辑会把 field 相关的数据清除,并且,由于 React 调用 ref 的时机确定了被 unmount 的 ref(null) 会在 mount 的组件的 ref(component) 之后,所以数据是一定会被清除的。

image

@benjycui
Copy link
Member

benjycui commented Nov 1, 2017

rc-form 本来就需要在组件 unmount 时清理对应 field 的数据,而现在无法判断 developers 到底是想 unmount 一个 filed 还是仅仅是想替换,所以个人认为在 rc-form 里面是无法解决了,还是在业务代码里面处理吧。

function NameField({ mode, ...restProps }) {
  return mode === 'select' ?
    <Select {...restProps} /> : <input {...restProps} />;
}

getFieldDecorator('name')(<NameField mode={mode} />)

@benjycui benjycui closed this as completed Nov 1, 2017
@afc163
Copy link
Member Author

afc163 commented Nov 1, 2017

  • mount 的时候记录绑定过的 component 到一个数组,只有数组最后一个数组是生效的。
  • unmount 的时候去清理数组相应的 component。

这样即使是先 mount 再 unmount 的话,也不会把所有数据都清空了。

@benjycui
Copy link
Member

benjycui commented Nov 2, 2017

这里的问题不在于 ref 引用不对,而是 rc-form 需要在组件 unmount 时清空对应的数据,ref(null) 其实和侵入组件 componentWillUnmount 效果是一样的。

所以现在的问题在于,B 的 componentWillMount 在 A 的 componentWillUnmount 之前,所以当 A 被 unmount 的时候,就把 B 的数据也清空了,而 rc-form 无法知道 A unmount 的原因是被替换还是 develoopers 不需要了。

@afc163 afc163 reopened this Nov 11, 2017
@afc163 afc163 mentioned this issue Nov 11, 2017
@afc163
Copy link
Member Author

afc163 commented Nov 14, 2017

didMount/didUpdate

  1. push
  2. slice(-2)

willUnmount

  1. unshift

读取 fieldMeta 和 ref 时以数组最后一个为准。


from @benjycui #116 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants