[英]display empty form while loading data in react
Ok, newbie alert, but I have a react component like below.好的,新手警报,但我有一个如下所示的反应组件。 I want to load user object and then show user.name and possible other nested properties, like user.address.street.
我想加载用户 object,然后显示 user.name 和可能的其他嵌套属性,如 user.address.street。
const ProfileDisplay =()=>
{
const [user, setUser] = useState(null);
useEffect(()=>{
async function populate(){
const user = await fetch('server/getUserProfile/'...);
setUser(user)
}
populate();
},[whatevs])
return (<FancyLookingForm>...<span>Your name is {user.name}</span>...</FancyLookingForm>);
}
... ...
During the time the user-object is loaded I want the form to be displayed, but empty.在加载用户对象期间,我希望显示表单,但为空。 The alternatives I see is either create a dummy object that looks like the one that will come from the server and use that as init object to useState().
我看到的替代方法是创建一个虚拟 object,它看起来像来自服务器的那个,并将其用作初始化 object 到 useState()。 The other alternative is to use an if null-check on every place I use the user-object.
另一种选择是在我使用用户对象的每个地方都使用 if null 检查。
I will do quite alot of forms, so I want to check if there is a better way to do this?我会做很多 forms,所以我想检查是否有更好的方法来做到这一点?
I have written a utility function that will help you.我写了一个实用程序 function 可以帮助你。
/**
* object is the forms data container in your example user
* property is field name e.g. name, age
*/
function getPropertryValue(object, property) {
if(!object) return "";
const keys = Object.keys(object);
const keysLength = keys.length;
for(let i= 0; i < keysLength; i++) {
const key = keys[i];
if(key == property) {
return object[key];
}
if(typeof object[key] === 'object'){
return utilFindHas(object[key], property);
}
}
return "";
};
So instead of using {user.name}
use getPropertyValue(user, "name")
It will return empty string if it doesn't exist yet.所以不要使用
{user.name}
使用getPropertyValue(user, "name")
如果它还不存在,它将返回空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.