Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

javascript - conditional rendering is not working in my functional component

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)}

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>

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

question from:https://stackoverflow.com/questions/65865227/conditional-rendering-is-not-working-in-my-functional-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
  );
};

Sandbox example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...