Javascript 使用三元运算符显示状态中的特定项
我无法用三元运算符显示条件输出。我想把一个值传递给一个函数,并且只显示来自状态的相关信息。我的代码:Javascript 使用三元运算符显示状态中的特定项,javascript,reactjs,react-native,conditional-operator,use-state,Javascript,Reactjs,React Native,Conditional Operator,Use State,我无法用三元运算符显示条件输出。我想把一个值传递给一个函数,并且只显示来自状态的相关信息。我的代码: import React, {useState} from 'react'; function Tasks({taskId, index}){ {task.parentId == taskId : } //Unable to code this. return( //show only tasks where parentId == taskId
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的任务。我应该怎么做呢?为了对代码进行最少的修改,您可以返回一个空片段或null:
function Tasks({ task }) {
return task.parentId == task.taskId
? (
<div>
<div> {task.title} </div>
<div> {task.body} </div>
</div>
)
: null;
}
由于任务呈现单个任务,考虑调用任务而不是任务
,对代码进行最少修改,可以返回空片段或null:function Tasks({ task }) {
return task.parentId == task.taskId
? (
<div>
<div> {task.title} </div>
<div> {task.body} </div>
</div>
)
: null;
}
因为任务呈现单个任务,考虑调用它任务而不是任务
。如果您只尝试用指定的ID呈现那些任务,则不必使用三元运算符。 函数renderTasksid{ 返回任务 .filter{taskId}=>taskId==id .map{title,body}=> {title} {body} ; }如果试图仅呈现具有指定id的任务,则可能不必使用三元运算符 函数renderTasksid{ 返回任务 .filter{taskId}=>taskId==id .map{title,body}=> {title} {body} ; } 我使用了.filtertask=>task.parentId==1,它可以工作。现在,我们也需要从状态中提取该值。非常感谢。我使用了.filtertask=>task.parentId==1,它可以正常工作。现在,我们也需要从状态中提取该值。非常感谢。