尝试使用 React 在 JSON 数据上应用三元运算符

Trying to apply Ternary Operator on JSON Data with React

我正在尝试将三元运算符应用于某些 JSON 数据,这些数据保存在本地的单独文件中。下面是 JSON:

[
{
  "id": 1,
  "company": "Photosnap",
  "logo": "./images/photosnap.svg",
  "new": true,
  "featured": true,
  "position": "Senior Frontend Developer",
  "role": "Frontend",
  "level": "Senior",
  "postedAt": "1d ago",
  "contract": "Full Time",
  "location": "USA Only",
  "languages": ["HTML", "CSS", "JavaScript"]
},
{
  "id": 2,
  "company": "Manage",
  "logo": "./images/manage.svg",
  "new": true,
  "featured": true,
  "position": "Fullstack Developer",
  "role": "Fullstack",
  "level": "Midweight",
  "postedAt": "1d ago",
  "contract": "Part Time",
  "location": "Remote",
  "languages": ["Python"],
  "tools": ["React"]
},
{
  "id": 3,
  "company": "Account",
  "logo": "./images/account.svg",
  "new": true,
  "featured": false,
  "position": "Junior Frontend Developer",
  "role": "Frontend",
  "level": "Junior",
  "postedAt": "2d ago",
  "contract": "Part Time",
  "location": "USA Only",
  "languages": ["JavaScript"],
  "tools": ["React"

现在我遇到的问题是,我有条件地想要显示一个按钮,具体取决于 "new" 是否为真。 据说特色按钮也是如此。 所以我在我的组件中写了一个三元运算符。

import React from 'react';

import './job-card.styles.css';

const JobCard = ({company, position, postedAt, contract, location, logo, featured, newJob })    => (

<div className="container">
   <div className='card'>
     <div className='companyName'>
        <img src={logo} alt="logo" width="100" height="100"></img>
    </div>
    <div className='content'>

        {{newJob} ? <button className='myButton'>New!</button> : null }
        {{featured} ? <button className='myDarkButton'>Featured</button> : null }
        <h2>{company}</h2>
        <h1>{position}</h1>
        <div className='details'>
            <h3>{postedAt} &#183;</h3>
            <h3>{contract} &#183;</h3>
            <h3>{location}</h3>
        </div>

      </div>
  </div>
 </div>
 )

 export default JobCard;

这只是一个卡片组件,并提供给另一个显示所有卡片的组件。

import React from 'react';

import './job-listing.styles.css';
import JobCard from '../job-card/job-card.component.jsx/job-card.component';
import { Component } from 'react';


class JobListing extends Component {
constructor() {
    super();
    this.state = {
        jobs: []
    }
  };

 componentDidMount() {
    fetch('/data.json')
    .then(response => response.json())
    .then(data => this.setState({jobs: data}))

   }
  render() {
    return (
        <div>
            {this.state.jobs.map(({id, ...otherJobProps}) =>(
            <JobCard key={id} {...otherJobProps} />
            ))}
        </div>
       )
     }
   }

  export default JobListing;

我得到的输出是,当 JSON 数据中的某些新内容或特色内容为假时,它们都呈现为真。不知道我错过了什么。任何帮助将不胜感激。

对于你的情况,你可以简单地做:

{newJob 
    && (<button className='myButton'>New!</button>)
}
{featured 
    && <button className='myDarkButton'>Featured</button>
}

之所以有效,是因为在 JavaScript 中,true && expression 始终计算为表达式

false && expression 总是计算为 false。

因此,如果条件为true,则&&之后的元素将出现在输出中。如果是 false,React 会忽略并跳过它。

nullundefined0""在JS中都是假值。


如果您确实需要两个选项,

Ternary operator 也是一个选项(例如):

<div>
    The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>

问题出在内部 {}

{{newJob} ? <button className='myButton'>New!</button> : null }
// ^ here

在 JSX 中,{} 表示一个 javascript 表达式。但是一旦你在一个表达式中,{} 就会回到正常的对象语法。这会丢弃您的三元组,因为您正在检查具有键 newJob 的对象是否为真。只需删除括号即可修复它:

{newJob ? <button className='myButton'>New!</button> : null }

关于 new 问题

我不想像这样解构 props,但为了让它像你已经拥有的那样工作,将 new 保留字解构为别名。这是一个简单的概念证明:

let test = [{ new: true }, { new: false }];

test.map(({new: isNew}) => console.log(isNew))

我希望保持数据结构不变。但这只是一种偏好。它还可以避免保留字问题。

let test = [{ new: true }, { new: false }];

test.map((value) => console.log(value.new))

首先,在 json 对象中我看到 属性 new: trueJobCard 组件接收 newJob 作为它的道具的一部分,不是 new.

为了回答您的问题,您会看到呈现的按钮,因为条件 {newJob} 是一个对象,其计算结果为真:

{{newJob} ? <button className='myButton'>New!</button> : null }

为什么?因为 {newJob} 与此相同:{ newJob: newJob } 创建一个名为 newJob 的 属性 对象,并为其分配您从中获得的 newJob 的值组件道具。

您要做的是以下其中一项:

{newJob ? <button className='myButton'>New!</button> : null }
{newJob && <button className='myButton'>New!</button> }