我正在编写一个WithLoading
组件,如果load为false,它将呈现子代,否则将呈现一个加载文本。子级包含来自ajax调用的响应参数。但是,当创建子项(不渲染子项)时,响应为null并引发异常。在渲染之前如何忽略异常?
这是代码示例
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div>
<MyComponent />
</div>
);
}
const WithLoading = props => {
if (props.loading) {
return <div>loading...</div>;
} else {
return props.children;
}
};
const MyComponent = () => {
const [response, setResponse] = useState(null);
useEffect(() => {
setTimeout(() => {
setResponse({ data: "data" });
}, 1000);
});
return (
<WithLoading loading={!response}>
<div>{response.data}</div>
</WithLoading>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
答案 0 :(得分:0)
可以通过以下方法解决:
在子组件MyComponent
的内部,您有response.data
/ null
,在该子组件的第一次安装时,您始终可以执行检查跟随undefined
,添加response && response.data
,将检查response &&
对象是否存在,如果存在,将返回所需的response
数组。
答案 1 :(得分:0)
使您的children
回调而不是元素:
const WithLoading = props => {
if (props.loading) {
return <div>loading...</div>;
} else {
return props.children();
}
};
const MyComponent = () => {
const [response, setResponse] = useState(null);
useEffect(() => {
setTimeout(() => {
setResponse({ data: "data" });
}, 1000);
});
const children = useCallback(
() => <div>{response.data}</div>,
[response]
);
return (
<WithLoading loading={!response}>
{children}
</WithLoading>
);
};