[英]React hook form useEffect not re-rendering functional component with call to another component
I'm trying to do aa react form using react-hook-forms, but I'm having trouble presenting data retrieved from an API call.我正在尝试使用 react-hook-forms 来做一个反应表单,但我无法呈现从 API 调用中检索到的数据。
I've sort of combined this example , which deals with asynchronously setting form values, and this example , which deals with nested arrays.我已经将这个处理异步设置表单值的示例和处理嵌套 arrays 的示例结合起来。
But for the life of me, I simply could not get it to work.但是对于我的一生,我根本无法让它发挥作用。 The JSON output of the API is something like this:
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*/}}
Here's the functional component:这是功能组件:
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;
And here's the functional component that calls:这是调用的功能组件:
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>
)
})}
)
}
I understand that the components are rendered before the useEffect is fired in UserTaskForm
, but how do I re-render it, such that defaultValues
in TaskTypeCards
don't log out an undefined
?我知道组件是在
UserTaskForm
中触发 useEffect 之前渲染的,但是我如何重新渲染它,这样TaskTypeCards
中的defaultValues
不会注销undefined
?
defaultValues
need to be passed as the props, to receive it as props in the TaskTypeCards components. defaultValues
需要作为 props 传递,以便在 TaskTypeCards 组件中将其作为 props 接收。
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.