I'm thinking this has something to do with "this", but I can't quite figure it out. I'm receiving an error that title is undefined and states the error stems from my Edit.js file. However, no error displayed until I attempted this.setState({ recipes: updateRecipe});
App.js
constructor() {
super();
this.titleChange = this.titleChange.bind(this);
//get initial state//
this.state = {
recipes: {
recipe1: {
title: 'Pacific Halibut',
time: 17,
description: 'the best halibut ever',
ingredient: ['halibut', "oil", "salt", "pepper", "kale"],
instruction: ['preheat oven at 350', 'sprinkle seasonings on fish', 'place foil on baking sheet', 'bake for 17 minutes']
},
recipe2: {
title: 'Cookies',
time: 12,
description: 'yummy cookies',
ingredient: ['cookie dough', 'chocolate chips', 'flour', 'butter', 'sugar'],
instruction: ['preheat oven at 350', 'mix ingreients together in a bowl', 'place a teaspoon of dough on a baking sheet one inch apart', 'bake for 12 minutes']
}
}
}
}
titleChange = (id) => (e) => {
const updateRecipe = Object.keys(recipes).map((recipe, sidx) => {
const target = e.target;
const name = target.name;
const value = target.value;
const recipes = {...this.state.recipes};
if (id !== sidx) return recipe;
return { ...recipe, [name]: value};
});
console.log(updateRecipe);
this.setState({ recipes: updateRecipe});
}
Edit.js
render(){
var id = (this.props.match.params.id);
return(
<input type="text" className="add-input" name="title" value={this.props.recipes[id].title} onChange={this.props.titleChange(id)}></input>
}
Thanks for the help.
答案 0 :(得分:1)
In this line you are iterating recipes
keys, but recipes
itself appears to be undefined at that point:
const updateRecipe = Object.keys(recipes).map((recipe, sidx) => {
Maybe you meant this instead?:
const updateRecipe = Object.keys(this.state.recipes).map((recipe, sidx) => {
答案 1 :(得分:0)
The problem is not related to binding with the correct context, but getting the data from recipes object in
value={this.props.recipes[id].title}
the id that you get from match.params.id may not be present in this.props.recipes
and hence it returns undefined, you need to add a check
value={this.props.recipes[id].title? this.props.recipes[id].title: ''}