Я немного озадачен этим, и я начинаю подозревать, что это что-то, и мои глаза просто остекленели. Я инициализирую this.state с помощью ingredients: [], а затем передаю его как опору дочернему компоненту <RecipePreview ingredients = {this.state.ingredients} instructions = {this.state.instructions}/>. В дочернем компоненте у меня есть следующий this.props.ingredients.map, который выдает следующую ошибку:
myRecipes-d3093398f8879b688ddb.js:41689 Uncaught TypeError: Cannot read property 'map' of undefined
Кажется, все настроено правильно, поэтому я не уверен, в чем ошибка. Следует отметить, что когда я удаляю карту и просто визуализирую содержимое опоры (скажем, [1,2,3]), она отображается без ошибок.
Ниже представлены два компонента. В этом файле есть другие компоненты, но я вставляю только два важных. Дайте мне знать, что вы думаете.
class CreateRecipe extends React.Component {
constructor(props) {
super(props);
this.state = {
ingredients: [[1,2,3]],
instructions: [[]]
};
this.addIngredient = this.addIngredient.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
addIngredient(quantity, unit, ingredient) {
let ingredients = this.state.ingredients;
ingredients.push([quantity, unit, ingredient]);
this.setState({ingredients: ingredients})
};
handleSubmit = event => {
};
validateForm() {
return this.state.ingredients !== [] || this.state.instructions !== [];
}
render() {
return (
<div className = {"list-container flex-row"}>
<form onSubmit = {this.handleSubmit}>
<AddIngredient addIngredient = {this.addIngredient}/>
<Button block bsSize = "small" disabled = {!this.validateForm()} type = "submit">
Add Recipe
</Button>
</form>
<RecipePreview ingredients = {this.state.ingredients} instructions = {this.state.instructions}/>
</div>)
}
}
class RecipePreview extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
Recipe Preview
{this.props.ingredients.map((ingredient, index) => {
return (
<div key = {`ingredient${index}`}>
{`${ingredient[0]} ${ingredient[1]} ${ingredient[2]}`}
</div>
)
})}
</div>
)
}
}
Спасибо. Переключу на this.state.ingredients.length === 0
ошибка возникает сразу же или только после того, как вы нажали <AddIngredient />?
Ознакомьтесь с разрешением выше! Я знал, что это что-то глупое. Ваш комментарий ранее заставил меня перепроверить другие мои компоненты.
Вы должны опубликовать свое «решение» в качестве ответа ниже, а не редактировать вопрос.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы получаете эту ошибку, потому что пытаетесь вызвать метод map для чего-то, что не определено. Одним из решений может быть проверка, существует ли массив перед отображением массива:
render() {
return (
<div>
Recipe Preview
{this.props && this.props.ingredients && this.props.ingredients.map((ingredient, index) => {
return (
<div key = {`ingredient${index}`}>
{`${ingredient[0]} ${ingredient[1]} ${ingredient[2]}`}
</div>
)
})}
</div>
)
}
РАЗРЕШАЮЩАЯ СПОСОБНОСТЬ
Комментарий ниже заставил меня еще раз просмотреть свои компоненты. Я обнаружил, что у меня есть дубликат <RecipePreview/> в другом компоненте. Проблема заключалась в том, что один из них был отрендерен без того, чтобы я пропустил опору.
class ListContainer extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className = {"list-container flex-row"}>
<MyRecipesList setRecipeAsSelected = {this.props.setRecipeAsSelected}
selectedRecipe = {this.props.selectedRecipe} recipeOwner = {this.props.recipeOwner}/>
<CreateRecipe selectedRecipe = {this.props.selectedRecipe}/>
<RecipePreview/>
<Instructions/>
{/*<Advertisements/>*/}
</div>)
}
}
К вашему сведению,
this.state.ingredients !== []всегда верно, потому что два массива никогда не равны друг другу.console.info([] === []).