这是我的代码:
useLayoutEffect (() => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const idBorrador = urlParams.get('tipo');
if (idBorrador) {
const fetchData = async () => {
try {
const response = await axios.get(`http://localhost:3000/getReport?id=${idBorrador}`);
document.getElementById("tipo").value = response.data.tipo;
document.getElementById("aux").value= response.data.nota;
} catch (error) {
console.error('Error fetching data for the draft:', error);
}
};
fetchData(); // Call the async function
}
}, []);
useEffect(() => {
async function seteo() {
try {
editor.setData(document.getElementById("aux").value);
} catch (error) {
console.error('Error fetching data:', error);
}
}
seteo()
}, []);
LayoutEffect 的想法是从数据库中获取数据。由于我调用 CKEditor 时似乎尚未加载它,因此我决定将 response.data.nota 的值存储在名为 aux 的隐藏输入中。
我尝试了两件事。首先,使用带有空 [] 的 useEffect 来调用 editor.setData,但我收到“编辑器未定义”错误。我也试过了
<CKEditor
editor={ClassicEditor}
id="cuerpo"
data={document.getElementById("aux").value}
name="cuerpo"
onReady={(editor) => {
它也不起作用。我该怎么办?
在
useLayoutEffect
中获取数据不是一个好主意,因为它是同步运行的。
我不知道为什么要预加载数据?
但是解决这个问题的方法是简单地在顶级组件树中的某个位置渲染组件,并像往常一样执行
useEffect
获取,因此当用户到达您的组件/页面时,数据将已经为他们加载。