瀏覽代碼

Fix layout effect ssr warning (#1155)

* fix: withField warning when ssr, close #1140

* test: update form test story
pointhalo 3 年之前
父節點
當前提交
af6b4a6676

+ 1 - 1
packages/semi-ui/form/_story/DynamicField/arrayFieldDemo.jsx

@@ -90,7 +90,7 @@ class ArrayFieldWithFormInitValues extends React.Component {
 
     change = () => {
         let number = this.formApi.getValue('number');
-        let newData = Array.from({ length: 2 }, (v, i) => ({
+        let newData = Array.from({ length: number }, (v, i) => ({
             name: `${i}-name`,
             time: `${i}-time`
         }));

+ 8 - 4
packages/semi-ui/form/hoc/withField.tsx

@@ -1,5 +1,5 @@
 /* eslint-disable max-lines-per-function, react-hooks/rules-of-hooks, prefer-const, max-len */
-import React, { useState, useLayoutEffect, useMemo, useRef, forwardRef } from 'react';
+import React, { useState, useLayoutEffect, useEffect, useMemo, useRef, forwardRef } from 'react';
 import classNames from 'classnames';
 import { cssClasses } from '@douyinfe/semi-foundation/form/constants';
 import { isValid, generateValidatesFromRules, mergeOptions, mergeProps, getDisplayName } from '@douyinfe/semi-foundation/form/utils';
@@ -19,6 +19,10 @@ import { noop } from "lodash";
 
 const prefix = cssClasses.PREFIX;
 
+// To avoid useLayoutEffect warning when ssr, refer: https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
+// Fix issue 1140
+const useIsomorphicEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
+
 /**
  * withFiled is used to inject components
  * 1. Takes over the value and onChange of the component and synchronizes them to Form Foundation
@@ -358,13 +362,13 @@ function withField<
         };
 
         // avoid hooks capture value, fixed issue 346
-        useLayoutEffect(() => {
+        useIsomorphicEffect(() => {
             rulesRef.current = rules;
             validateRef.current = validate;
         }, [rules, validate]);
 
         // exec validate once when trigger inlcude 'mount'
-        useLayoutEffect(() => {
+        useIsomorphicEffect(() => {
             if (validateOnMount) {
                 fieldValidate(value);
             }
@@ -373,7 +377,7 @@ function withField<
 
         // register when mounted,unregister when unmounted
         // register again when field change
-        useLayoutEffect(() => {
+        useIsomorphicEffect(() => {
             // register
             if (typeof field === 'undefined') {
                 // eslint-disable-next-line @typescript-eslint/no-empty-function