BooleanField 与 FunctionField 将数字更改为布尔值

lli*_*oor 1 admin-on-rest

我有疑问,我相信这会对其他开发人员有所帮助。我的 API 端有一个布尔字段“is_active”,但它返回 0 或 1,而不是 TRUE 或 FALSE。我想用<FunctionField/>它来包裹<BooleanField/>但它不起作用。请有人帮忙。

这是我的代码:

<FunctionField source="is_active" label="is_active" render={(record) => record.is_active ? true : false}>
  <BooleanField/>
</FunctionField>
Run Code Online (Sandbox Code Playgroud)

该列仍为空白。

谢谢。

Den*_*nge 8

我认为您误解了该FunctionField组件。它渲染 prop 的结果render。您想要实现的目标是:

<FunctionField source="is_active" label="is_active" render={(record,source) => 
    <BooleanField record={{...record,is_active:!!record.is_active}} source={source}/>}/>
Run Code Online (Sandbox Code Playgroud)

但这不太好。更好的方法是包装dataProvider/restClient并确保数据是布尔值。

// In FixMyDataFeature.js
export default restClient => (type, resource, params) => restClient(type,resource,params).then(response=>
   if(resource === 'Resource_with_numeric_is_active_field`){
      return {
         data: mutateIsActiveFieldToBoolean(response.data)
      }
   }
   else{
      return response;
   }
);
Run Code Online (Sandbox Code Playgroud)

并使用 Admin 调用它:

<Admin dataProvider={FixMyDataFeature(dataProvider)}... />
Run Code Online (Sandbox Code Playgroud)