如果数据存在或不存在,最好的呈现方式?
Best way to render if data exists or not?
我有一个加载一些数据的 graphql 查询 运行。我将该数据传递给一个组件,并传递我为检查数据而创建的函数。如果数据片段存在则渲染传入的组件,如果不存在则渲染 null。
export const GET_VESSEL = gql`
query vesselById($id: ID!) {
vesselById(id: $id) {
flagCode
shipName
}
}
`;
const checkData = (data, component) => data ? component : null;
<div>
{checkData(flagCode, <Flag code={`${flagCode}`} height="15" />)}
{checkData(shipName, <p>${flagCode}</p>)}
</div>
我想知道是否有更简单的方法或者这是否是执行此操作的好方法?或者有什么建议。
你可以做到
const checkData = (data, component) => Boolean(data) ? component : null;
最简单的解决方案是
{flagCode && <Flag code={flagCode} height="15" />}
{shipName && <p>${flagCode}</p>}
在有限的情况下需要 null 但您的示例不是其中之一。
我有一个加载一些数据的 graphql 查询 运行。我将该数据传递给一个组件,并传递我为检查数据而创建的函数。如果数据片段存在则渲染传入的组件,如果不存在则渲染 null。
export const GET_VESSEL = gql`
query vesselById($id: ID!) {
vesselById(id: $id) {
flagCode
shipName
}
}
`;
const checkData = (data, component) => data ? component : null;
<div>
{checkData(flagCode, <Flag code={`${flagCode}`} height="15" />)}
{checkData(shipName, <p>${flagCode}</p>)}
</div>
我想知道是否有更简单的方法或者这是否是执行此操作的好方法?或者有什么建议。
你可以做到
const checkData = (data, component) => Boolean(data) ? component : null;
最简单的解决方案是
{flagCode && <Flag code={flagCode} height="15" />}
{shipName && <p>${flagCode}</p>}
在有限的情况下需要 null 但您的示例不是其中之一。