【问题标题】:React component not rendering inside .map with if statement使用 if 语句反应组件未在 .map 内呈现
【发布时间】:2020-05-12 11:33:13
【问题描述】:

请帮忙。如果 list.display = true,我有一个要加载的组件。我可以做一个控制台日志来确认什么时候应该显示列表并且它工作正常。但是,组件不会加载。如果我将组件从 .map 循环中取出,它会完美运行。

谢谢

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 node.js reactjs loops components


    【解决方案1】:

    我认为你完全错过了 javascript 的 array::map 函数的用途,它应该为每个被调用的元素返回一个值。它返回一个与迭代的数组长度相同的数组。你实际上是在过滤你的结果。

    Filter/Map - 过滤数组结果然后映射到响应 JSX

    {
      lists
        .filter((list: listInterface) => list.display) // exploit truthy/falsey display value
        .map((list: listInterface) => (
        <ToDoApp list={lists[0]} />
      ))
    }
    

    Reduce - 允许将结果直接“过滤”到 React JSX 中

    {
      lists.reduce((filteredLists: listsInterface, list: listInterface) => {
        if (list.display) {
          filteredLists.push(<ToDoApp list={lists[0]} />);
        }
        return filteredLists
      }, [])
    }
    

    【讨论】:

      【解决方案2】:

      地图函数需要返回一个值。

      lists.map( (list: listInterface, index:number) => {
          if (list.display) {
              console.log("List " + list.listName + " ordered");
              return <ToDoApp list={lists[0]} /> 
              }
          })
      

      【讨论】:

        【解决方案3】:
            {
              lists.map((list: listInterface, index: number) => {
                if (list.display === true) {
                 return <ToDoApp list={lists[0]} />
        
                }
              })
            }
        

        在 if 条件中添加 return 以呈现 JSX

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-04
          • 1970-01-01
          • 2017-05-12
          • 1970-01-01
          • 2018-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多