代码之家  ›  专栏  ›  技术社区  ›  mayorsanmayor

从嵌套组件返回映射迭代器的正确方法是什么?

  •  4
  • mayorsanmayor  · 技术社区  · 7 年前

    在尝试从渲染方法返回(更复杂的)值时,我经常会产生各种错误。其中大部分,我都能解决。但这一次,组件根本不渲染,但是。。。没有控制台错误。

    class RenderMe1 extends React.Component {
        constructor(props) {
            super(props);
            this.state = { list: ['A','B','C'] }
        }
        render() {
            return(
            <div>
                <div>
                    /* === Works === */
                    { this.state.list.map((object, index) => this.state.list[index] ) }
                </div>
            </div>);
        }
    }
    
    class RenderMe2 extends React.Component {
        constructor(props) {
            super(props);
            this.state = { list: ['0','0','0'] }
        }
        render() {
            return(
            <div>
                <div>
                    /* === Doesn't Work === */
                    { this.state.list.map((object, index) => { this.state.list[index] } ) }
                </div>
            </div>);
        }
    }
    
    ReactDOM.render(<RenderMe1 />, document.getElementById("root"));  // works
    ReactDOM.render(<RenderMe2 />, document.getElementById("root2")); // doesn't work
    

    出于实践目的,我在浏览器中使用babel插件,因此使用JSX语法。

    3 回复  |  直到 7 年前
        1
  •  2
  •   InfiniteStack    7 年前

    括号内的代码仍然有效,因为 计算

    但在这种特殊情况下,问题在于arrow函数本身。下面有一个特定的规则:跳过{}方括号时,语句 实际上,它被视为返回值,而不必使用return关键字。这会稍微清除代码。但是一旦添加{}括号,必须使用return关键字显式返回其中的内容。以下内容将解决您的问题:

    { this.state.list.map((object, index) => { return(this.state.list[index]) } ) }
    

    nested components 本教程通过几个正确的返回用例来确定问题。你的只是执行语句。

    希望这有帮助。

        2
  •  3
  •   patrick    7 年前

    第二个你有,所以它不会返回任何东西。这是修改后的代码

    class RenderMe2 extends React.Component {
        constructor(props) {
            super(props);
            this.state = { list: ['0','0','0'] }
        }
        render() {
            return(
            <div>
                <div>
    
                    { this.state.list.map((object, index) => { return this.state.list[index] } ) }
                </div>
            </div>);
        }
    }
    

    this.state.list.map(listItem => listItem);

        3
  •  1
  •   Dacre Denny    7 年前

    第二种方法不起作用的原因是带有箭头函数的句法潜规则。

    当您用{和}包装一个包含单个语句的arrow函数时,该arrow函数将有效地等效于返回 undefined .

    例如:

    (object, index) => { this.state.list[index] }
    

    function(object, index) { 
    
       this.state.list[index];
    
       // Notice that nothing is returned
    }
    

    { } ,正如您在工作版本中所做的:

    { this.state.list.map((object, index) => this.state.list[index] ) }
    

    { this.state.list.map(function(object, index) {
    
       // The function is returning something
       return this.state.list[index]
    }
    

    这个 return 与非政府组织“免费”的行为 { .. } 箭头功能,是第一个版本工作,而后一个版本失败的原因。更多信息, see this MDN article