【发布时间】:2020-09-27 12:52:58
【问题描述】:
我正在尝试有条件地渲染结果不佳的组件。我已经阅读了许多教程和 Stack Overflow 问题,但我无法完成这项工作。你能帮帮我吗?
条件组件是一个数据可视化的地理地图,只有在获取的 json 文件具有“code”键时才应该呈现。换句话说,我有几十个 json,其中一些包含地理地图信息,但不是全部。我一直在 jsx 中尝试布尔和不同类型的三元运算符,但是每次在侧边栏中单击无地图项时,React 都会尝试渲染 Map 子组件并给出“代码”(键)未定义的错误.这可能是什么原因?以下是我的代码:
App.js
function App() {
const [files, setFiles] = useState([]);
const [items, setItems] = useState([]);
const [product_id, setProduct_id] = useState(13);
const [mapCode, setMapcode] = useState(0);
useEffect(() => {
fetch("/sidebar")
.then((res) => res.json())
.then((data) => {
setItems(data);
});
}, []);
useEffect(() => {
fetch(`/data/${product_id}`)
.then((res) => res.json())
.then((data) => {
setFiles(data);
if ("code" in data[0]) setMapcode(1);
else setMapcode(0);
console.log(mapCode);
});
}, [product_id]);
function HandleSelection(e) {
setProduct_id(e);
}
如果获取的产品数据包含“code”键,则在 useEffect 中,每次在侧边栏中单击项目(产品)时,我都会更改 mapCode。 console.log(mapCode) 给出了正确的结果。
下面是 App.js 的 return() 里面的基本代码。我尝试了几种方法来进行条件渲染。
<div className="col-6">
<Files files={files} />
</div>
<div className="col-3">
{/*Boolean(mapCode) && <Map files={files} />*/}
{/*mapCode === true && <Map files={files} />*/}
mapCode === true ? <Map files={files} /> : <div>No map</div>
</div>
我一直在想 useEffect 是否适合使用 setMapcode(0) 和 setMapcode(1)?
【问题讨论】:
标签: reactjs components conditional-statements