我在 React (Typescript) 中有一些名为“Blocks”的组件,代码如下:
const Blocks = (props) => {
const [loading, setLoading] = useState(0);
useEffect(() => {
setLoading(props.loading);
}, [props.loading]);
return (
<div className="blocks">
{props.loading && <Loader />}
<Block store={store} />
<Block store={store} />
<Block store={store} />
<Block store={store} />
<Block store={store} />
</div>
);
}
在 reducer 的帮助下,我跟踪每个 Block 组件的加载状态,并在所有加载完成后停止显示
<Loader />
元素。
基于
useLocation();
我想用每页正确的块填充块组件,但每个都预加载(以及稍后的转换)。
Block.tsx 看起来像这样:
import {connect} from "react-redux";
import {useEffect, useState} from "react";
import Block1 from "./blocks/Block1forHomepage"; // not needed when dynamic loading the correct component
const Block = (props) => {
const [state, setState] = useState("block is fetching data...");
useEffect(() => {
props.startLoading();
let timer1 = setTimeout(() => {
props.stopLoading();
setState("");
}, 2000);
return () => {
clearTimeout(timer1);
};
}, []);
return (
<>
{state ? (
state
) : (
<>
<Block1forHomepage /> <!-- Make dynamic somehow -->
</>
)}
</>
);
}
const mapStateToProps = (state: { LoadingReducer: { loading: any; }; }) => {
return {
loading: state.LoadingReducer.loading
};
};
const mapDispatchToProps = (dispatch: (arg0: { type: string; }) => any) => ({
startLoading: () =>
dispatch({
type: "START_LOADING"
}),
stopLoading: () =>
dispatch({
type: "STOP_LOADING"
})
});
export default connect(mapStateToProps, mapDispatchToProps)(Block);
我的目标是用每页的正确块填充每个静态
<Block />
组件。所以主页必须有一个包含 6 个组件的数组,联系页面必须有其他 6 个组件,但填充相同的静态<Block />
组件。
添加这样的组件时:
<Block store={store} currentComponent={<Block1forHomepage />} />
我得到一个错误,因为
const Block = (props, currentComponent) => { // doesn't work
不接受像 currentComponent 这样的另一个参数。
如何在一个一直存在的静态组件中根据URL加载组件?
预加载组件
.. 并且可能对每个块进行转换
任何帮助表示赞赏。