我正在使用下面的包
react-if
。
https://www.npmjs.com/package/react-if
但是我的子组件没有渲染。我正在尝试这样
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Example Component={App} />
</React.StrictMode>
);
这是我的示例组件。
export const Example = ({ Component }) => {
const fetchData = () => {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation (e.g., fetching data from a server)
setTimeout(() => {
console.log('oooooooooo');
// Simulating a successful response
const data = { message: 'Data fetched successfully' };
return resolve(data);
// Simulating an error
// reject(new Error('Failed to fetch data'));
}, 2000); // Simulating a delay of 2 seconds
});
};
return (
<div>
<If condition={fetchData()}>
<Fallback>Loading data ...</Fallback>
<Then>
{(data) => (
<>
<span>Here ish your data:{JSON.stringify(data)}</span>
<Component />
</>
)}
</Then>
<Else>{(error) => <span>Failed to load data because </span>}</Else>
</If>
</div>
);
};
有时它显示组件..有时不显示..不知道我哪里做错了
keepAlive={true}
keepAlive?: 布尔值
False(默认):每次卸载之前都会取消承诺
正确:即使在卸载组件或更改 Promise 属性之后,Promise 也可以实现
使用
StrictMode
,每个组件都会获得 mounted
-> unmounted
-> mounted
,并且使用 keepAlive
它将保持承诺状态。
<If condition={fetchData()} keepAlive={true}>
<Fallback>Loading data ...</Fallback>
<Then>
{(data) => (
<>
<span>Here ish your data:{JSON.stringify(data)}</span>
<Component />
</>
)}
</Then>
<Else>{(error) => <span>Failed to load data because </span>}</Else>
</If>
https://stackblitz.com/edit/vitejs-vite-w7hy6e?file=src%2Fexample.tsx