Arrays React组件未识别。作为函数筛选
因此,我正在为食物配方制作一个react应用程序,并从JSON文件中提取数据。由于某些原因,配方的.filter和.map没有显示为函数。非常感谢您的帮助 在大多数示例中,似乎可以在“渲染”下添加此信息。我是一个既有编码又有反应的noob,所以我确信这是用户错误Arrays React组件未识别。作为函数筛选,arrays,json,reactjs,Arrays,Json,Reactjs,因此,我正在为食物配方制作一个react应用程序,并从JSON文件中提取数据。由于某些原因,配方的.filter和.map没有显示为函数。非常感谢您的帮助 在大多数示例中,似乎可以在“渲染”下添加此信息。我是一个既有编码又有反应的noob,所以我确信这是用户错误 import React from 'react'; import ReadInput from'./readInput'; import '../Styles/Home.css'; class Input extends Reac
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>
)
}
应用程序文件
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>
)
}
从“React”导入React;
从“./Input”导入输入;
从“../data.json”导入配方;
类应用程序扩展了React.Component{
建造师(道具){
超级();
}
render(){
返回(
)
}
}
导出默认应用程序 如果
此.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>
);
});
const recipes=this.props.data;
const menu=Object.keys(recipeKey).filter((recipeKey)=>recipeKey[recipeKey].id==this.state.value)
.map(recipeKey=>
返回(
{食谱[recipeKey].dish}
{食谱[recipeKey].配料}
);
});
首先过滤this.props.data
的键,只获得与状态中id匹配的配方的键。
然后映射(仍然使用对象的键而不是值进行映射)并创建列表
请注意,我将key属性移动到了
标记,这是因为您需要在映射返回的组件中使用该属性,而不是在其子组件中
另外,在
单击中,onClick属性接收菜单,但它应该会在单击按钮时接收一个要执行的函数。使用超时函数或检查您的响应,它可能会在您的函数运行之前稍后出现。使用timeout并检查它
if (timerid) {
clearTimeout(timerid);
}
timerid = setTimeout(() => {
this.reqMaq(obj['fkmaqid'])
}, 2000);
您在哪里使用此输入组件?似乎此.props.data
未定义或不是数组。@garrettmaring我添加了使用输入的应用程序。。。菜谱是我的json文件中的内容,我不认为你可以像那样导入一个json文件,并期望它像一个数组一样工作。您需要从JS文件导出数组,或者在将其作为数组使用之前读取JSON文件并对其进行分析。控制台中是否存在任何错误?为您的组件提供一个静态defaultProps={data:[]}
,为安全起见,还需要检查您传递的数据类型,在导入后立即尝试登录以查看其是否正常工作。学习如何调试。
if (timerid) {
clearTimeout(timerid);
}
timerid = setTimeout(() => {
this.reqMaq(obj['fkmaqid'])
}, 2000);