React中的条件渲染/三元问题

时间:2019-02-10 03:22:26

标签: javascript reactjs

我正在尝试根据ajax调用返回的数据呈现男性或女性图标。 返回的对象看起来像这样。

https://rickandmortyapi.com/api/character/

如果在移动设备上或没有JSON视图,则一个字符对象如下所示:

{
info: {
count: 493,
pages: 25,
next: "https://rickandmortyapi.com/api/character/?page=2",
prev: ""
},
results: [
{
id: 1,
name: "Rick Sanchez",
status: "Alive",
species: "Human",
type: "",
gender: "Male",
origin: {
name: "Earth (C-137)",
url: "https://rickandmortyapi.com/api/location/1"
},
location: {
name: "Earth (Replacement Dimension)",
url: "https://rickandmortyapi.com/api/location/20"
},
image: "https://rickandmortyapi.com/api/character/avatar/1.jpeg",
episode: [
"https://rickandmortyapi.com/api/episode/1",
"https://rickandmortyapi.com/api/episode/2",
"https://rickandmortyapi.com/api/episode/3",
"https://rickandmortyapi.com/api/episode/4",
"https://rickandmortyapi.com/api/episode/5",
"https://rickandmortyapi.com/api/episode/6",
"https://rickandmortyapi.com/api/episode/7",
"https://rickandmortyapi.com/api/episode/8",
"https://rickandmortyapi.com/api/episode/9",
"https://rickandmortyapi.com/api/episode/10",
"https://rickandmortyapi.com/api/episode/11",
"https://rickandmortyapi.com/api/episode/12",
"https://rickandmortyapi.com/api/episode/13",
"https://rickandmortyapi.com/api/episode/14",
"https://rickandmortyapi.com/api/episode/15",
"https://rickandmortyapi.com/api/episode/16",
"https://rickandmortyapi.com/api/episode/17",
"https://rickandmortyapi.com/api/episode/18",
"https://rickandmortyapi.com/api/episode/19",
"https://rickandmortyapi.com/api/episode/20",
"https://rickandmortyapi.com/api/episode/21",
"https://rickandmortyapi.com/api/episode/22",
"https://rickandmortyapi.com/api/episode/23",
"https://rickandmortyapi.com/api/episode/24",
"https://rickandmortyapi.com/api/episode/25",
"https://rickandmortyapi.com/api/episode/26",
"https://rickandmortyapi.com/api/episode/27",
"https://rickandmortyapi.com/api/episode/28",
"https://rickandmortyapi.com/api/episode/29",
"https://rickandmortyapi.com/api/episode/30",
"https://rickandmortyapi.com/api/episode/31"
],
url: "https://rickandmortyapi.com/api/character/1",
created: "2017-11-04T18:48:46.250Z"
},

这是我尝试过的:

    let gender= props.character.gender;
    {gender="Male" ? <img src="../male.png"/> : <img src="../female.png"/>}

但是每个人都渲染成男性,我不知道为什么。

将这些内容渲染到称为角色的组件中,角色的道具由每个角色的对象组成。我知道我正确地访问了该值,因为我已使用它来将字符“男性”或“女性”一词呈现给角色的卡片。

1 个答案:

答案 0 :(得分:1)

您正在使用分配(expr),而不是比较(====),请尝试以下操作:

==

在您的示例中,{gender === "Male" ? <img src="../male.png"/> : <img src="../female.png"/>} gender的值并求值为truthy的值,因此每次返回Male