gpt4 book ai didi

reactjs - 渲染 useEffect 后如何加载组件

转载 作者:行者123 更新时间:2023-12-04 07:25:00 25 4
gpt4 key购买 nike

我正在使用 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)}
/>
但是 dataReactFormBuilder未呈现,因为最初未加载 useEffect。我如何重新加载 ReactFormBuilder在 useEffect 被渲染之后?

最佳答案

我猜你正在寻找这样的东西:

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)}
/>
)}

关于reactjs - 渲染 useEffect 后如何加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68264312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com