条件渲染在我的功能组件中不起作用 [英] conditional rendering is not working in my functional component
问题描述
我正在尝试在下一段代码中渲染if(年龄<18)的组件
I am trying to render a component if (age<18) in the next block of code
var split_dob = dateOfBirth.split("-");
var month = split_dob[1];
var day = split_dob[2];
var year = split_dob[0];
var dob_asdate = new Date(year, month, day);
var today = new Date();
var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
var age = (mili_dif / (1000 * 3600 * 24 * 365.25));
console.log(age);
if(age<18){setEligible(true)}
这是useState挂钩:
here's useState hook:
const [uneligible,setEligible] = React.useState(
false // default value
)
这是我尝试呈现它的方式:
and here's how I am trying to render it:
<div>{uneligible&& <Alert variant="filled" severity="error">
This is an error alert — check it out!
</Alert>}</div>
在实际项目中没有错误,只是组件未渲染 我在这里做了最小化的代码版本,但是在渲染时仍然有问题: https://codesandbox.io/s/thirsty-sara -jiomm?file =/src/App.js
in the actual project there's no errors, just the component not rendering and I made minimised version of the code here but it still has problem in rendering: https://codesandbox.io/s/thirsty-sara-jiomm?file=/src/App.js
推荐答案
您实际上不需要此处的状态.只需使用const uneligible = age<18
并摆脱useState
代码,它就可以正常工作.如果将uneligible
设置为状态,则会创建一个渲染循环,因为设置该循环会触发重新渲染,然后重新设置该状态并触发另一个重新渲染,等等.
You don't actually need state here. Just use const uneligible = age<18
and get rid of the useState
code, and it will work okay. If you put uneligible
in the state you create a render loop, as setting it triggers a re-render, which sets the state again and triggers another re-render, etc.
const ProfilePage = (props) => {
var dateOfBirth = "2007-01-01";
var split_dob = dateOfBirth.split("-");
var month = split_dob[1];
var day = split_dob[2];
var year = split_dob[0];
var dob_asdate = new Date(year, month, day);
var today = new Date();
var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
var age = mili_dif / (1000 * 3600 * 24 * 365.25);
console.log(age);
const uneligible = age < 18;
return (
<div>
{uneligible && (
<Alert variant="filled" severity="error">
This is an error alert — check it out!
</Alert>
)}
</div>
);
};
这篇关于条件渲染在我的功能组件中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!