2017-10-20 110 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> 
    ) 
    }