简体   繁体   English

如何从 map 函数中的 forEach 返回一个 div?

[英]How can I return a div from forEach inside map function?

I am building a new component in React to display filters.我正在 React 中构建一个新组件来显示过滤器。 My filter data looks like this:我的过滤器数据如下所示:

{countries: [0: {value: 'England'}, 1: {value: 'Australia'}], continents: []}

In my render function I want to return a div for each value inside an object (England, Australia).在我的渲染函数中,我想为对象(英格兰、澳大利亚)内的每个值返回一个 div。 Currently, I don't get anything rendered to the Dom.目前,我没有得到任何渲染到 Dom 的东西。

render() {
        const {i18n, t} = this.props;
    
        return <div className={'filter'}>
            <ul className={'filter-list'}>
                {
                    Object.keys(this.props.filters).map(i => {
                        this.props.filters[i].forEach(
                            element => {
                                console.log('element', element)
                                return <p>{element.value}</p>
                            }
                        )
                    })
                }
            </ul>
        </div>;
    }

Does anyone know how I could achieve this/return the value properly?有谁知道我怎样才能实现这个/正确返回值?

forEach does not return anything. forEach不返回任何内容。 You'll need to use map instead:您需要使用map代替:

{
  Object.keys(this.props.filters).map((i) => {
    // Switched to .map and added `return`
    return this.props.filters[i].map((element) => {
      return <p>{element.value}</p>;
    });
  });
}

This code will create a 2 dimensional array of elements, but react supports that.此代码将创建一个二维元素数组,但 react 支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何完全从函数内部的.forEach内部退出 - How can I completely exit from inside a .forEach that is inside a function 如何从我的 map function 内部返回 HTML 块? - How can I return the HTML block from inside of my map function? 如何从要返回的函数内部的函数内部返回函数的值 - How can I return a value for a function from inside a function inside the function I wish to return 如何从javascript函数中的.then内部返回值? - How can I return a value from within a .then inside a javascript function? 使用嵌套的forEach循环而没有临时变量时,如何从主函数返回值? - How can I return a value from the main function when using a nested forEach loop without a temporary variable? 如何在我的返回 function 中 map 多个数据对象? - How can I map multiple data objects inside my return function? 我可以从 div 调用 function 并让它返回多个属性吗? - Can I call a function from a div and have it return multiple attributes? 如何监视一个函数并使用茉莉花从另一个函数内部返回模拟值? - How can I spy on a function and return a mock value from inside another function using jasmine? 如何在 React JS 中的 map function 中返回 forEach - How to return a forEach within a map function in React JS 如何防止 forEach 循环内的 function 被多次调用? (在大多数情况下,它会重复出现) - How can I prevent function inside of forEach loop from being called more than once? (For the most part it repeats predictably)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM