2017-10-20 113 views
1

下面是我使用(作为道具被传递到组件)对象的基本布局:阵营:调用地图功能里面的函数

bigObject { 
    overview: { 
     *not being used for current concern* 
    }, 
    code: { 
     1: { 
      textArray: [*array of length 4 to 8*], 
      imgSrc: "string goes here" 
     }, 
     2: { 
      textArray: [*array of length 4 to 8*], 
      imgSrc: "string goes here" 
     }, 
     3: { 
      textArray: [*array of length 4 to 8*], 
      imgSrc: "string goes here" 
     }, 
    } 
} 

我的构造函数:

constructor(props) { 
    super(props); 
    this.state = { 
     projectName: this.props.projectName, 
     info: bigObject[this.props.projectName] 
    } 
    this.renderInfo = this.renderInfo.bind(this); 
    this.renderText = this.renderText.bind(this); 

    console.log(this.state.info); 
} 

我想要做的是遍历代码对象,以便对于每个imgSrc,对象中的文本数组与迭代以创建列表元素沿照片边。

renderInfo() { 
    return Object.keys(this.state.info.code).map(function(key, index) { 
     return (
      <div className="code-snippet" id={name + key} key={key}> 
       <div className="code-description"> 
        <ul> 
         {() => this.renderText(key)} 
        </ul> 
       </div> 
       <div className="code-img"> 
        <img src={"/project-images/MongoScraper/" + placeholder[key].img} alt=""/> 
       </div> 
      </div> 
     ) 
    }); 
} 

每个IMG呈现正是我想要的,但renderText方法不是通过textArray迭代像我想:

renderText(key) { 
    console.log("hello world") //doesn't log 
    let placeholder = this.state.info.code; 
    return placeholder[key].text.map(function(keyValue, index) { 
     return (
      <li>{placeholder[key].text[index]}</li> 
     ) 
    }); 
} 

渲染()方法:

render() { 
    return (
     <div className="container code-descriptor-div"> 
      {this.renderInfo()} 
     </div> 
    ) 
} 

由于词法范围问题(“不能读取未定义的属性”结果不使用箭头函数),因此我在调用renderText方法时使用了箭头函数,但我知道该方法不是c完全一致,因为控制台没有记录“Hello world”。

当我在render()方法内部调用renderText方法时,它会正确地呈现列表元素,但这样做并不适用于我构造其他组件的方式。

有没有办法像我想要的遍历textArray?

回答

4
  1. 你实际上并没有调用你的函数。你正在传递一个新的函数。

变化

{() => this.renderText(key)} 

到:

{this.renderText(key)} 
  • 你固定在错误的位置的词法作用域。您仍然在使用function作为地图。
  • 变化:

    .map(function(key, index) { 
    

    到:

    .map((key, index) => { 
    

    当写作阵营代码,使用箭头功能无处不在。这将是一种非常罕见的情况,您需要需要才能使用function关键字。

    +0

    这帮助了很多。谢谢。 –

    0

    你不能从一个异步函数里面返回一个新的语句,比如已经在主函数中的map()。您必须在父函数中传递回调。尝试是这样的:

    function foo(callback){ 
        const bigObject = [{ 
         textArray: [*array of length 4 to 8*], 
         imgSrc: "string goes here" 
        }, { 
         textArray: [*array of length 4 to 8*], 
         imgSrc: "string goes here" 
        }]; 
        if(bigObject.length>0){ 
         bigObject.map((obj)=>{ 
         callback(obj); 
         }); 
        } 
    } 
    

    现在你可以调用从bigObject所有值渲染方法里面,像这样:

    render(){ 
        return (
        <div> 
         {this.foo(e){ console.log(e.textArray); }} 
        </div> 
    ) 
    }