【发布时间】:2019-07-28 17:36:56
【问题描述】:
我在实现这个(简单?)目标时遇到了问题。
在反应显示页面上,我想在“乐器部分”标题下列出学生乐器部分的无序列表,这很容易。状态的异步设置有效,在我使用的渲染中:
let instrumentList = this.state.instrumentSections.map((instrument)=>{
return <li>{instrument}</li>;
});
在我使用的回报的相关部分:
<h3>Your section(s):</h3>
<ul>{instrumentList}</ul>
当学生还没有被分配到任何乐器组时,麻烦就来了(因此状态设置为[])。我想显示“乐器组”,然后显示“你还不是乐队的一员”。而不是“Instrument Section(s)”,然后什么都没有,这就是上面代码发生的情况。
我已尝试以多种方式使用if then(如下所示,轻微变化试图达到相同的效果),但无论我尝试什么,对于分配了乐器部分的学生,信息都会正确显示,但仍会继续显示“仪器部分”,然后什么都没有。如果我在这种情况下console.log(instrumentList),它会返回[]。
如果然后在渲染中:
let instrumentList;
const noBand = "You are not part of a band yet. Please make sure that your instructor adds you to the right band through Ensemble.";
if (this.state.instrumentSections !== [] ) {
instrumentList = this.state.instrumentSections.map((instrument)=>{
return <li>{instrument}</li>;
});
} else {
instrumentList = noBand;
}
我是否需要在异步获取的.then 中尝试使用这个if then 魔法?其他想法?
更新编辑 3/12:
我在玩弄大家的建议。我看到了内联条件运算符应该做什么,但是由于(我认为)return 的位置,我无法像 CocoHot 重构它的方式将它调整到我的代码中。
这是return 中包含的整个class 的重构:
render(){
const noBand = "You are not part of a band yet. Please make sure that your instructor adds you to the right band through Ensemble.";
const instrumentList = this.state.instrumentSections.map((instrument)=>{
<li>{instrument}</li>;
});
return instrumentList.length > 0 ? instrumentList : noBand;
return (
<div className="text-center student-show">
<h1>{this.state.student.first_name} {this.state.student.last_name}</h1>
<h3>Your section(s):</h3>
<ul>{instrumentList}</ul>
</div>
)
}
我很确定上面的主要问题是 render 不能有多个返回,我认为这意味着我必须将条件运算符行放入第二个 return 并得到摆脱第一个return。到目前为止,我一直在尝试这样做但没有成功,所以我也尝试将操作符行放入 const instrumentList = 块中,但没有成功。
还有什么建议吗?我知道解决方案已经很接近了,感谢大家迄今为止的帮助。
编辑 2: 在尝试重构为 vanilla if else 格式以查看是否可以这样工作时,我注意到代码在长度检查中没有返回 true,因为它设置为> 0(因此空数组评估为假)。我将运算符更改为== 0,现在它似乎可以正确跳闸,至少在原版格式中是这样。让noBand 显示仍然没有运气。
【问题讨论】:
-
不是测试
!== [],而是测试this.state.instrumentSections.length > 0的长度,原因是[]的新实例不是===[]的现有实例。[] === []是false
标签: javascript reactjs if-statement fetch-api stateful