我正在使用 npm 包 react-form-builder2
。
const [stateform, setstateform] = useState([]);
useEffect(() => {
axios
.get(
`${server}/api/getservice/6`,
{ headers }
)
.then((response) => {
if (response.data[0].intakeForm) {
setstateform(JSON.parse(response.data[0].intakeForm));
}
})
.catch((error) => {
console.log(error);
});
}
}, []);
console.log("stateform", stateform); // [{id: "0DA5756A-BDF4-4D57-97CD-5F173361C29E", element: "Label", text: "Label", static: true, required: false}]
<ReactFormBuilder
data={stateform}
onPost={(e) => change(e)}
/>
但是 data
中的 ReactFormBuilder
没有呈现,因为 useEffect 最初没有加载。呈现 useEffect 后如何重新加载 ReactFormBuilder
?
答案 0 :(得分:1)
使用 stateform
有条件地呈现。
...
return (
{ stateform.length
? <ReactFormBuilder
data={stateform}
onPost={(e) => change(e)}
/>
: 'loading...'
}
);
...
答案 1 :(得分:1)
我猜你正在寻找这样的东西:
const [stateform, setstateform] = useState([]);
const [loadingState, setLoadingState] = useState('not_loaded'); // not_loaded | loading | loaded | error
useEffect(() => {
setLoadingState('loading')
axios
.get(
`${server}/api/getservice/6`,
{ headers }
)
.then((response) => {
setLoadingState('loaded');
if (response.data[0].intakeForm) {
setstateform(JSON.parse(response.data[0].intakeForm));
}
})
.catch((error) => {
setLoadingState('error');
console.log(error);
});
}
}, []);
{loadingState === 'not_loaded' && 'whatever you want to be here'}
{loadingState === 'loading' && 'loading'}
{loadingState === 'error' && 'something went wrong'}
{loadingState === 'loaded' && (
<ReactFormBuilder
data={stateform}
onPost={(e) => change(e)}
/>
)}