我有以下简单用例:
组件ServerRendered
用于呈现使用属性url
从服务器检索的标记。在ServerRendered
中,我使用useEffect从后端加载标记,将状态设置为当前标记并将其呈现在div中。
属性init
可选地指定应在呈现标记后执行的功能。
呈现标记后如何运行init函数?
/* eslint-disable react/no-danger */
import React, {useState, useEffect} from 'react';
import axios from 'axios';
type ServerRenderedPropsType = {
url: string,
init?: () => void,
};
function ServerRendered(props: ServerRenderedPropsType) {
const [html, setHtml] = useState('');
useEffect(() => {
async function fetchData() {
const result = await axios(props.url);
setHtml(result.data.title);
}
fetchData();
}, [props.url]);
return <div dangerouslySetInnerHTML={{__html: html}} className="serverRendered" />;
}
export default ServerRendered;
答案 0 :(得分:3)
收到数据后,您只需做另一件事即可
import React, {useState, useEffect, useCallback} from 'react';
import axios from 'axios';
type ServerRenderedPropsType = {
url: string,
init?: () => void,
};
function ServerRendered(props: ServerRenderedPropsType) {
const [html, setHtml] = useState('');
const fetchData = useCallback(async () => {
const result = await axios(props.url);
setHtml(result.data.title);
}, [props.url])
useEffect(() => {
fetchData();
}, [fetchData]);
useEffect(() => {
// do what you want here
if (!html) return;
props.init()
}, [html])
return <div dangerouslySetInnerHTML={{__html: html}} className="serverRendered" />;
}
export default ServerRendered;