简体   繁体   中英

multiple if statements in a React.js component

I am working on my portfolio and I bumped into this problem. This component gets tasks(array) and sortBy(either 'all', 'true', or 'false'). The problem is, even though I pass 'all' value of sortBy, the second if statement gets called.

const TaskListTable = ({ tasks, sortBy }) => {
  let filteredTasks;
  let sortByBoolean;
  if (sortBy === 'all') {
    filteredTasks = tasks;
  }
  if (sortBy === 'true' || 'false') {
    sortByBoolean = sortBy === 'true';
    filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
  }
  console.log(sortBy);
  console.log(sortByBoolean);
  console.log(filteredTasks);

  const withTasks = (
    <div className='task-table'>
      <UtilButton purpose='add' pushUrl='/task-add' />
      <div className='task-table-head'>
        <div>Date</div>
        <div>Task</div>
        <div>Status</div>
        <div></div>
      </div>
      {filteredTasks.map(({ _id, ...others }) => (
        <TaskList key={_id} id={_id} {...others} />
      ))}
    </div>
  );
  const withoutTasks = <UtilPage purpose='emptyData' />;

  return <Fragment>{tasks.length > 0 ? withTasks : withoutTasks}</Fragment>;
};

I solved this problem with this code below instead of using 2 if statements. But I'd still want to know why the code above with 2 if statements don't work.

const sortByBoolean = sortBy === 'true';
const filteredTasks = sortBy !== 'all' ? tasks.filter((task) => task.completed === sortByBoolean) : tasks;

thank you in advance

This part...

if (sortBy === 'true' || 'false') {
  //...
}

...should be...

if (sortBy === 'true' || sortBy === 'false') {
  //...
}

You didn't check the condition if sortBy equals 'false' but you checked the value 'false' itself. This will return true because the string 'false' is truthy .
So currently both of your if statements are true and are executed.

If you write two If statements consecutively then definately it will execute both of this two . This is the behaviour of If statement .

So you may used if else if method , also write || statement separately to solve this problem.

   if (sortBy === 'all') {
    filteredTasks = tasks;
  }
  else if (sortBy === 'true' || sortBy === 'false') {
    sortByBoolean = sortBy === 'true';
    filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
  }

because your if condition is not as expected because both if will be executed to skip second if when first is passed add else

if (sortBy === 'all') {
  filteredTasks = tasks;
} else if (sortBy === 'true' || sortBy === 'false') {
  sortByBoolean = sortBy === 'true';
  filteredTasks = tasks.filter((task) => task.completed === sortByBoolean);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM