2017-07-06 199 views
0

因此,我正在爲食譜製作反應應用程序,並從JSON文件中提取數據。出於某種原因,配方的.filter和.map不能作爲函數顯示。任何幫助不勝感激。React組件不能識別.filter作爲函數

它大部分的例子看起來像你可以在渲染下添加這個信息。我是一個雙方編碼和反應noob,所以我相信這是用戶錯誤。

import React from 'react'; 
import ReadInput from'./readInput'; 
import '../Styles/Home.css'; 

class Input extends React.Component{ 
    constructor(props) { 
     super(props); 
    this.state = { 
     value:'' 
    } 
    this.handleName = this.handleName.bind(this); 
}; 
handleName(e){ 
    console.log('handleName') 
    if(e === 'chicken'){ 
      this.setState({value: 1}) 
     } else if (e === 'beef') { 
      this.setState({value: 2}) 
     } else if (e === 'rice'){ 
      this.setState({value: 3}) 
     } 

} 


render(){ 
    const menu = this.props.data.filter((recipe) => { 
      if(recipe.id === this.state.value){ 
      return recipe.dish; 
     } 
    }) 
    .map(recipe => { 
     return(
      <div> 
      <li key={recipe.id}>{recipe.dish}</li> 
      <li >{recipe.ingredients}</li> 
      </div> 
     ) 
    }) 

    return(
     <div> 
      <ReadInput 
       onChange={this.handleName} /> 
      <button className="homeButton" onClick={this.menu}>Click</button> 
      <ul className='listStyle'> 
       {menu} 
      </ul> 
     </div> 
    ) 
} 

}

export default Input; 

app文件

import React from 'react'; 
import Input from'./Input'; 
import recipes from'../data.json'; 

class App extends React.Component{ 
    constructor(props) { 
     super(); 

} 
render(){ 
    return(
     <div> 
      <Input data={recipes} /> 
     </div> 
    ) 
} 

}

出口默認應用程序;

+0

你在哪裏使用這個輸入組件?看起來像'this.props.data'是未定義的或不是數組。 – garrettmaring

+0

@garrettmaring我添加了應用程序,我使用的是輸入...食譜是我的json文件的內容 – angelHank

+0

我不認爲你可以導入一個像這樣的JSON文件,並期望它像一個數組一樣工作。您可能需要從JS文件中導出數組,或者讀取JSON文件並在使用數組之前解析它。 – djfdev

回答

0

如果this.props.data是一個對象,則不能直接映射或過濾它。我想,這應該工作:

const recipes = this.props.data; 
const menu = Object.keys(recipes).filter((recipeKey) => recipes[recipeKey].id === this.state.value) 
.map(recipeKey => 
    return (
    <div key={recipes[recipeKey].id}> 
     <li>{recipes[recipeKey].dish}</li> 
     <li>{recipes[recipeKey].ingredients}</li> 
    </div> 
); 
}); 

首先您過濾this.props.data的鑰匙,你只能拿到鑰匙的匹配狀態的ID的食譜。 然後映射(仍然映射對象的鍵,而不是值)並創建列表。

請注意,我將關鍵屬性移動到了<div>標記,這是因爲您需要在地圖返回的組件中使用此屬性,而不是在它的子項中。

另外,在<button className="homeButton" onClick={this.menu}>Click</button>中,onClick屬性接收菜單,但它應該接收單擊按鈕時執行的函數。