Skip to content

Commit

Permalink
fix: Fixed bug where useWatch did not update as expected when setFiel…
Browse files Browse the repository at this point in the history
…dsValue was set (#126)

Co-authored-by: wuxiuran <wuxiuran@kezaihui.com>
  • Loading branch information
wuxiuran and wuxiuran authored Oct 17, 2024
1 parent 79ef7cb commit 861d91a
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zaihui/hui-design",
"version": "0.0.1-beta.72",
"version": "0.0.1-beta.76",
"description": "小程序组件库",
"templateInfo": {
"name": "mobx",
Expand Down
6 changes: 5 additions & 1 deletion src/components/Form/FormItem/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ import { useId } from '../../../utils/hooks'
*/
const Item: React.FC<HuiFormItemProps> = (props) => {
const context = useContext<FieldContext>(Context)
const { registerWatch, getFieldValue, setFieldValue } = context
const { registerWatch, getFieldValue, setFieldValue, removeFieldValue } =
context
const listContext = useContext<FormListContextProps>(FormListContext)
const [renderType, setRenderType] = useState<keyof ItemType>('other')
const [, update] = useState({})
Expand Down Expand Up @@ -180,6 +181,9 @@ const Item: React.FC<HuiFormItemProps> = (props) => {
validatorRules(localValue)
}, [localValue])

// 组件卸载后移出字段
useEffect(() => () => removeFieldValue(path), [path, removeFieldValue])

useEffect(() => {
const unMount = registerWatch(id, {
name: path,
Expand Down
10 changes: 6 additions & 4 deletions src/components/Form/FormStore/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,15 +150,17 @@ class FormStore {
}

notifywatchList(name?: string | string[]): void {
if (!name) {
this.fieldWatchList.forEach((fns) => fns.forEach((fn) => fn(this.store)))
}
this.watchList.forEach((field: any) => {
const { onStoreChange } = field
const fieldName = toString(field.name)

if (this.fieldWatchList.has(fieldName)) {
this.fieldWatchList.get(fieldName).forEach((fn) => fn(this.store))
}

if (name) {
if (this.fieldWatchList.has(fieldName)) {
this.fieldWatchList.get(fieldName).forEach((fn) => fn(this.store))
}
if (toString(name) === fieldName) {
onStoreChange()
}
Expand Down

0 comments on commit 861d91a

Please sign in to comment.