反应:渲染箭头函数内定义的方法?

时间:2019-10-30 15:25:24

标签: javascript reactjs nested arrow-functions

你好朋友!我希望你一切都好。

我有一个名为WorldInfo的箭头函数,它的父组件正在使用props向下传递一个对象,对于此示例,我只是调用object。现在,在WorldInfo中,我也想解析并列出items中的object,所以我创建了方法serverInfoTabList来接受object并推入其中.map。我的问题是编译时,我的浏览器在定义serverInfoTabList或在WorldInfo自己的返回函数中调用时,无法识别 Line 7:5: 'serverInfoTabList' is not defined no-undef Line 34:22: 'serverInfoTabList' is not defined no-undef

这是错误和代码本身。

const WorldInfo = (props) =>  {

    serverInfoTabList = (object) => {
        if (object != undefined){
            return object.item.map((item) => {
                const time = Math.trunc(item.time/60)
                return (
                    <li key={item._id}>{item.name}
                        <br/>
                        Minutes Online: {time}
                    </li>
                );
            });
        }
    }

    return (
        props.object!= undefined ? 
        <div className={props.className}>
            <h1>{props.world.map}</h1>
            {/* <img src={props.object.image}/> */}
            <div>
                <ul>  
                    {serverInfoTabList(props.object)}
                </ul>
            </div>
        </div>
        : 
        null
    );
}

{{1}}

感谢您与我的朋友!

1 个答案:

答案 0 :(得分:2)

您忘记了const声明

const serverInfoTabList = (object) => {
    /* ... */
}

另一个问题是您正在访问例如props.world不存在的属性。另外,您正在通过未定义的属性props.object.item进行映射。我已经更正了您的沙箱

const WorldInfo = props => {
  const serverInfoTabList = object => {
    return Object.keys(object).map(key => {
      const item = object[key];
      const time = Math.trunc(item.time / 60);
      return (
        <li key={item._id}>
          {item.name}
          <br />
          Minutes Online: {time}
        </li>
      );
    });
  };

  return props.object ? (
    <div className={props.className}>
      <h1>{props.world.map}</h1>
      {/* <img src={props.object.image}/> */}
      <div>
        <ul>{serverInfoTabList(props.object)}</ul>
      </div>
    </div>
  ) : null;
};

class Todo extends Component {
  render() {
    const object = { item1: { _id: 1, time: 1 }, Item2: { _id: 2, time: 2 } };
    return (
      <div>
        <WorldInfo object={object} world={{ map: "foo" }} />
      </div>
    );
  }
}

Edit React example