Я довольно новичок в React и создаю приложение со стеком MERN для создания, чтения, обновления и удаления рецептов, но я получаю предупреждение от React, что у меня нет уникального ключа для моих предметов рецепта. Однако, когда я обновляю sh моего браузера, предупреждение исчезает, и у моего объекта рецепта теперь есть идентификатор. Похоже, что идентификатор рецепта не публикуется до тех пор, пока элементы рецепта не будут перерисованы. Я не получаю предупреждение, если я передаю индекс в качестве ключа, но я просто очень хочу понять, почему я продолжаю получать эту ошибку при попытке использовать идентификатор, сгенерированный из MongoDB.
class RecipeContiner extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
ingredients: "",
summary: "",
recipes: []
}
}
//GET RECIPES
componentDidMount() {
const url = 'http://localhost:5000/recipes/';
axios.get(url)
.then((res) => {
this.setState({ recipes: res.data })
}).catch(err => {
console.log(err);
});
}
onChangeHandler = (e) => {
this.setState({ [e.target.name]:e.target.value})
}
//POST RECIPE
onSubmitHandler = (e) => {
e.preventDefault();
const recipe = {
title: this.state.title,
ingredients: this.state.ingredients,
summary: this.state.summary
}
const url = 'http://localhost:5000/recipes/add';
axios.post(url, recipe)
.then(res => console.log('new recipe!', res.data));
this.setState({
recipes: [...this.state.recipes, recipe],
});
e.target.reset();
}
render() {
return (
<div>
<form onSubmit={this.onSubmitHandler}>
<label>Title:</label>
<input type="text" onChange={this.onChangeHandler} name="title"/>
<label>Ingredients:</label>
<input type="text" onChange={this.onChangeHandler} name="ingredients"/>
<label>Summary:</label>
<input type="text" onChange={this.onChangeHandler} name="summary"/>
<input type="submit" value="Submit" />
</form>
<RecipeList recipes={this.state.recipes} />
<Fab color="primary" aria-label="add">
<AddIcon />
</Fab>
</div>
);
}
//RECIPE LIST COMPONENT
const RecipeList = (props) => {
console.log('props.recipes', props.recipes)
const recipes = props.recipes;
return (
<div>
<ul>
{recipes.map((recipe, index) => (
<RecipeItem
key={recipe._id}
title={recipe.title}
ingredients={recipe.ingredients}
summary={recipe.summary}
/>
))}
</ul>
</div>
);
}
//RECIPE ITEM COMPONENT
const RecipeItem = (props) => {
return (
<li>
<div>{props.title}</div>
<div>{props.ingredients}</div>
<div>{props.summary}</div>
</li>
)
}
}```
[1]: https://i.stack.imgur.com/aZtEO.png