React component not rendering inside .map with if statement(使用 if 语句反应组件未在 .map 内呈现)
问题描述
请帮忙.如果 list.display = true,我有一个要加载的组件.我可以做一个控制台日志来确认何时应该显示列表并且它工作正常.但是,组件不会加载.如果我将组件从 .map 循环中取出,它会完美运行.
Please help. I have a component that I am trying to load if list.display = true. I am able to do a console log confirming when the list should be displayed and it works properly. However, the component does not load. If I take the component out of the .map loop it works perfectly.
谢谢
return (
<div className="container">
<h1>To Do App</h1>
<p>Create a list:</p>
<form>
<label htmlFor="list">
<input type="text" name="list" id="list" onChange={e => setInputListName(e.target.value)}/>
<button onClick={addList}>Create List</button>
</label>
</form>
<div className="listsContainer">
{
lists.map( (list: listInterface, index:number) =>
(<button onClick={() => loadList(index)}>{list.listName}</button>)
)
}
{
lists.map( (list: listInterface, index:number) => {
if (list.display == true) {
<ToDoApp list={lists[0]} />
console.log("List " + list.listName + " ordered");
}
})
}
</div>
</div>
);
推荐答案
我认为你完全错过了 javascript 的 array::map
函数的目的,它应该为每个元素返回一个值 它被调用.它返回一个与迭代的数组长度相同的数组.你实际上是在过滤你的结果.
I think you completely miss the purpose of javascript's array::map
function, it should return a value for every element it is called on. It returns an array that is the same length as the array it iterated over. You are actually filtering your results a bit.
Filter/Map - 过滤数组结果然后映射到响应 JSX
Filter/Map - Filter array results then map to react JSX
{
lists
.filter((list: listInterface) => list.display) // exploit truthy/falsey display value
.map((list: listInterface) => (
<ToDoApp list={lists[0]} />
))
}
Reduce - 允许将结果直接过滤"到 React JSX 中
Reduce - Allows to "filter" results directly into react JSX
{
lists.reduce((filteredLists: listsInterface, list: listInterface) => {
if (list.display) {
filteredLists.push(<ToDoApp list={lists[0]} />);
}
return filteredLists
}, [])
}
这篇关于使用 if 语句反应组件未在 .map 内呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 if 语句反应组件未在 .map 内呈现


- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07