尝试在React组件中对.map函数的结果使用.filter

时间:2017-10-19 12:20:55

标签: javascript arrays reactjs object higher-order-functions

我正在React制作一个鸡尾酒食谱书应用程序,我正在尝试实现一种按成分过滤掉鸡尾酒的搜索功能。对于我的主页,我映射每个用户,然后每个用户提交并在页面上呈现它们。我试图这样做,以便在第二张地图之后,根据搜索字段中的值来过滤每个提交。以下是我尝试过的方法:

<div><SearchContainer>
             <input type="text" placeholder="Search" onChange={this.handleChange}/>
             </SearchContainer>

        <div style={styles.root}>
            <GridList
                cellHeight={180}
                style={styles.gridList}
                padding={50}
            >
                {this.state.users.map((user, index) => {                      
                     console.log(user.submitted) 
                    return (

                        user.submitted.map((submission, index) => {
                            return submission 
                            let filteredSubmissions = submission.filter(
                                (submission) => {
                                    return submission.recipe.toLowerCase().indexOf(
                                        this.state.search.toLowerCase()) !== -1;

                                }
                            )                  
                            return (

                                    <GridTile
                                        key={filteredSubmissions._id}
                                        title={filteredSubmissions.name}

                                        subtitle={<span>{filteredSubmissions.recipe}</span>}
                                    >
                                    <img alt={filteredSubmissions.name} onClick={() => this.setState({redirect: true, submissionId: submission._id, userId: user._id})} src={submission.img} />

                                    </GridTile>   
                            )
                        }
                        )
                    )
                })}
            </GridList>
        </div>
        </div>

错误讯息:

Objects are not valid as a React child (found: object with keys {_id, recipeLink, recipe, img, submittedBy, name, comments}). If you meant to render a collection of children, use an array instead.
    in GridList (at ExperimentalHomePage.js:66)
    in div (at ExperimentalHomePage.js:65)
    in div (at ExperimentalHomePage.js:61)
    in ExperimentalHomePage (created by Route)
    in Route (at App.js:20)
    in Switch (at App.js:19)
    in div (at App.js:17)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:16)
    in MuiThemeProvider (at App.js:15)
    in App (at index.js:7)

我不确定我是不是使用了正确的语法,或者我的逻辑是否完全有缺陷,但如果有人能指出我正确的方向,我会非常感激。

1 个答案:

答案 0 :(得分:0)

React无法渲染对象。 filteredSubmissions.recipe看起来这可能是你的罪魁祸首。尝试将其设为字符串JSON. stringify(filteredSubmissions.recipe)并再次测试。