React component not rendering inside .map with if statement

≡放荡痞女 提交于 2020-02-05 14:54:10

问题


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.

Thank you

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>
    );

回答1:


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 - 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 - 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
  }, [])
}



回答2:


A map function need to return a value.

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]} />

        }
      })
    }

add return in the if condition to render the JSX



来源:https://stackoverflow.com/questions/59925252/react-component-not-rendering-inside-map-with-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!