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

resetFields会导致自定义组件销毁并重新加载 #106

Closed
se7en00 opened this issue Mar 26, 2020 · 1 comment
Closed

resetFields会导致自定义组件销毁并重新加载 #106

se7en00 opened this issue Mar 26, 2020 · 1 comment

Comments

@se7en00
Copy link

se7en00 commented Mar 26, 2020

我在antd(4.0) form中使用一个自定义组件, 该自定义组件每次加载会异步加载一些数据

const MeetingTab = ({ onChange, value = 0 }) => {
    const [selectTab, setSelectTab] = useState<number>(value)
    const [meetingRooms, setMeetingRooms] = useState<number[]>([])
    const handleMettingTabChange = useCallback(
        value => {
            setSelectTab(value)
            if (onChange) {
                onChange(value)
            }
        },
        [onChange]
    )
    useEffect(() => {
        if (!meetingRooms.length) {
            //异步请求
            request().then(data => {
                setMeetingRooms(data)
            })
        }
    }, [meetingRooms])

    const renderTab = useMemo(() => {
        return meetingRooms.map((value, index) => {
            const isActive = selectTab === value ? "active" : ""
            return (
                <li onClick={() => handleMettingTabChange(value)} key={index} className={isActive}>
                    {value}
                </li>
            )
        })
    }, [handleMettingTabChange, meetingRooms])

    return <div>{renderTab}</div>
}

当使用form.resetFields时, 会导致该组件会重新加载一次, 导致多了一次请求!
当然通过props可以解决这一问题,但是我只想在组件里进行异步请求, 又不想在resetFields时再请求一次, 有什么好的办法吗?

@zombieJ
Copy link
Member

zombieJ commented Apr 7, 2020

reset 会重置整个 Field 以消除之前存在的任何副作用,受控组件数据管理应该是纯粹的。如果就是要 mount 就加载,可以用第三方库管理请求做 cachable。比如 swr

@zombieJ zombieJ closed this as completed Apr 7, 2020
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

No branches or pull requests

2 participants