使用三元运算符显示状态中的特定项目

Use ternary operator to show specific items from state

我无法使用三元运算符显示条件输出。我想将一个值传递给一个函数并仅显示来自该州的相关信息。我的代码:


import React, {useState} from 'react';

function Tasks({taskId, index}){

 {task.parentId == taskId : }       //Unable to code this.

  return(       //show only tasks where parentId == taskId
         <div>
           <div> {task.title} </div>
           <div> {task.body} </div>
         </div>
        )
}

function App(){

    const[tasks, setTasks] = useState([
        {
            taskId: 1,
            title: 'Task1',
            body: 'This is the body of the task1',
            isComplete: false,
            parentId: 0
        },
        {
            taskId: 2,
            title: 'Task2',
            body: 'This is the body of the task2',
            isComplete: false,
            parentId: 1
        },      
        {
            taskId: 3,
            title: 'Task3',
            body: 'This is the body of the task3',
            isComplete: false,
            parentId: 1
        },
        {
            taskId: 4,
            title: 'Task4',
            body: 'This is the body of the task4',
            isComplete: false,
            parentId: 3
        }
    ])

    return(
            <div style={{marginLeft: 20}}>
                <h1>ToDo</h1>

                {tasks.map((task, index)=>
                    <Tasks 
                        taskId=1
                    />
                )}
            </div>
        )
}

export default App;

所以,我只想显示 parentId 为 1 的任务。我应该怎么做?

为了对代码进行最少的修改,您可以 return 空片段或 null:

function Tasks({ task }) {
    return task.parentId == task.taskId
        ? (
            <div>
                <div> {task.title} </div>
                <div> {task.body} </div>
            </div>
        )
        : null;
}

(确保使用 parentId,而不是 pasrentId,和 task.taskId,而不是 taskId - 你没有将 task 作为道具传递目前,因此更改代码以执行此操作:<Tasks task={task} />)

但我认为在调用方中使用 .filter 更有意义:

return (
    <div style={{ marginLeft: 20 }}>
        <h1>ToDo</h1>
        {tasks
            .filter(task => task.parentId === task.taskId)
            .map(task => <Task task={task} />)
        }
    </div>
)

(因为 Tasks 呈现单个任务,考虑将其称为 Task 而不是 Tasks

如果您尝试仅呈现具有指定 id 的那些任务,您可能不必使用三元运算符。

function renderTasks(id) {
  return tasks
    .filter(({ taskId }) => taskId == id)
    .map(({ title, body }) => (
      <div>
        <div> {title} </div>
        <div> {body} </div>
      </div>
    ));
}