【发布时间】:2017-07-06 23:19:58
【问题描述】:
所以我正在为食物食谱制作一个反应应用程序,并从 JSON 文件中提取数据。由于某种原因,食谱的 .filter 和 .map 没有显示为函数。非常感谢任何帮助。
大多数示例看起来您可以在渲染下添加此信息。我是一个既编码又反应的菜鸟,所以我确定这是用户错误。
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;
应用文件
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>
)
}
}
导出默认应用;
【问题讨论】:
-
你在哪里使用这个输入组件?似乎
this.props.data要么未定义要么不是数组。 -
@garrettmaring 我添加了我正在使用输入的应用程序......食谱是我的 json 文件中的内容
-
我认为您不能只导入这样的 JSON 文件并期望它像数组一样工作。您要么需要从 JS 文件中导出数组,要么读取 JSON 文件并解析它,然后再像数组一样使用它。
-
控制台有错误吗?
-
为您的组件提供
static defaultProps = { data: [] },为了安全起见,还要检查您传递的数据类型,在导入后立即登录以查看它是否正常工作。学习如何调试。