簡體   English   中英

React hook form useEffect 不會通過調用另一個組件來重新渲染功能組件

[英]React hook form useEffect not re-rendering functional component with call to another component

我正在嘗試使用 react-hook-forms 來做一個反應表單,但我無法呈現從 API 調用中檢索到的數據。

我已經將這個處理異步設置表單值的示例和處理嵌套 arrays 的示例結合起來。

但是對於我的一生,我根本無法讓它發揮作用。 API 的 JSON output 是這樣的:

{"daily": { "last_received_date": "2020-08-03 11:04:18 UTC+8", "tasks": [
  { "id": "1", "freq": "d", "prog": 0, "max": 5, "reward": 1000 },
  { "id": "2", "freq": "d", "prog": 0, "max": 1, "reward": 1000 },
  { "id": "3", "freq": "d", "prog": 0, "max": 3, "reward": 1000 }]}, 
 "weekly": {/*Similar to daily*/}}

這是功能組件:

const UserTaskForm = (data) => {
    const [TaskId, setTaskId] = useState();
    const [TaskArray, setChallengeArray] = useState([]);
    const { register, control, handleSubmit, getValues, reset, errors } = useForm();
    const onSubmit = (formData) => {console.log(formData);};

    useEffect(() => {
        async function fetchData() {
            try {
                let result = await dbGetUserTasks(data.userId);
                console.log(result);
                const tempArray = [];
                const formData = JSON.parse(result[0].challenges);
                tempArray.push(formData.daily);
                tempArray.push(formData.weekly);
                setTaskId(JSON.parse(result[0].id));
                setChallengeArray(tempArray);
            } catch (error) { console.error(error); }
        }

        fetchData();
    }, []);

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <Box paddingTop={2} paddingBottom={2}>
                <Button type="submit" style={{ marginLeft: "auto" }}>Save Changes</Button>
            </Box>
            {TaskArray ? <Spinner animation="border" /> : <TaskTypeCards{...{ control, register, TaskArray, getValues, errors }} />}            
        </form>     
    );
}

export default UserTaskForm;

這是調用的功能組件:

export default function TaskTypeCards({ control, register, defaultValues, errors }) {
    console.log(defaultValues); // <--------------- Undefined.
    const { fields, append, remove } = useFieldArray({ control, name: "test" });

    useEffect(() => {
        console.log(defaultValues); // <--------------- Undefined.
    }, [defaultValues])

    return(
        {defaultValues.map((challenge, index) => {
            return (
                <Card>
                    Blah blah this doesn't work anyway
                </Card>
            )
        })}
    )
}

我知道組件是在UserTaskForm中觸發 useEffect 之前渲染的,但是我如何重新渲染它,這樣TaskTypeCards中的defaultValues不會注銷undefined

defaultValues需要作為 props 傳遞,以便在 TaskTypeCards 組件中將其作為 props 接收。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM