【问题标题】:Render Object properties in React在 React 中渲染对象属性
【发布时间】:2017-09-28 23:46:05
【问题描述】:

我有一个这样的对象

export const otherInformation = [
{
    "FAQ": ['Getting started guide', 'Selling policy'],
    "Help & Support": ['Help guide', 'Selling policy'],
    "Legal": ['Terms of Use', 'Privacy Policy']
}]

我的代码

class Information extends Component {
    render() {
        const otherInformationLoop = otherInformation.map((value, key) => {
            return (
                <div>
                    <div className="col-md-4" key={key}>
                        <div className="dashboard-info">

                            {Object.keys(value).map((val, k) => {
                                return (<h4 k={k}>{val}</h4>)
                                })
                            }

                        </div>
                    </div>
                </div>
            )
        })

        return (
            { otherInformationLoop }
            // <div></div>
        );
    }
}

我在循环对象时遇到问题。

得到的错误是这样的

Information.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object

如何循环遍历对象,从而得到得到的结果

提前致谢。任何帮助表示赞赏

【问题讨论】:

    标签: javascript reactjs object


    【解决方案1】:

    你正在渲染一个数组,但你只能从你的 react 组件返回一个块,将你的 map 函数包装在一个 div 中

    class Information extends Component {
        render() {
            const otherInformationLoop = otherInformation.map((value, key) => {
                return (
                    <div>
                        <div className="col-md-4" key={key}>
                            <div className="dashboard-info">
    
                                {Object.keys(value).map((val, k) => {
                                    return (<h4 k={k}>{val}</h4>)
                                    })
                                }
    
                            </div>
                        </div>
                    </div>
                )
            })
    
            return (
    
                <div>{ otherInformationLoop }</div>
            );
        }
    }
    

    【讨论】:

    • 实际上,render 方法返回了一个具有单个 otherInformationLoop 属性的对象。在 React 16+ 中只需返回该值,不带任何类型的括号即可(但每个外部 div 都需要一个 key prop)。
    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 2018-10-04
    • 2016-12-31
    • 2019-06-08
    • 1970-01-01
    • 2019-03-01
    • 2022-12-11
    • 2019-11-15
    相关资源
    最近更新 更多