类型错误:类别未定义

时间:2021-01-13 06:00:13

标签: reactjs react-redux

我让我的程序发疯了。我试图从我遇到的前一个问题中进行一些调整,我遇到了一个不允许的参数:我遇到的 :recipe 问题。我基本上将属性封装在一个 recipe 对象中,以希望与由于强参数而发送到后端的内容相匹配。我指出了进行这些更改的位置。这个问题是否得到解决取决于现在解决这个当前问题的方法。在进行了一些更改后,我使用 redux 在前端调整了我的调度有效负载的操作类型后,不断收到此 TypeError: Categories is undefined

switch(action.type){
        case 'Add_Recipe':
            const recipe = {
               recipe:{   <-----I encapsulated everything within a recipe value and recipe as my key
                name: action.name,
                ingredients: action.ingredients,
                chef_name: action.chef_name,
                origin: action.origin,
                // categoryId: action.categoryId,
                category: action.category
               }
            }

            return{
                ...state,
                recipes: [...state.recipes, recipe],
            }
       
        default:
            return state
        
    }
}

为了确保我的一切都与此更改一致,我还更改了 RecipeInput 组件中的初始状态和 setState。 注意:我特意在此代码段中省略了事件处理程序

import React, { Component } from 'react'
import  Categories  from './Categories.js'



class RecipeInput extends Component{
    constructor(props){
        super(props)
        this.state = {
            recipe:{  <-----I encapsulated everything within a recipe value and recipe as my key
            category: [],
            name:'',
            ingredients: '',
            chef_name: '',
            origin: ''
            }
        }
        this.handleNameChange.bind(this)
        this.handleOriginChange.bind(this)
        this.handleChefChange.bind(this)
        this.handleIngChange.bind(this)


        
    }

    

    componentDidMount(){
        let initialCats = [];
        const BASE_URL = `http://localhost:10524`
        const CATEGOREIS_URL =`${BASE_URL}/categories`
        fetch(CATEGOREIS_URL)
        .then(resp => resp.json())
        .then(data => {
            
            initialCats = data.map((category) => {
                return category
            })
            console.log(initialCats)
                this.setState({
                    category: initialCats,
                })   
            });
    }


    handleSubmit = (event) =>{
        event.preventDefault();
        this.props.postRecipes(this.state)
        this.setState({
        recipe:{   <-----I encapsulated everything within a recipe value and recipe as my key
        name:'',
        ingredients: '',
        chef_name: '',
        origin: ''
        }
     })
    }

    
        

    render(){
        return(
            <div>
                <form onSubmit={this.handleSubmit}>
                    <Categories category={this.state.category}/>
                    <div>
                    <label for='name'>Recipe Name:</label>
                    <input type='text' value={this.state.name} onChange={this.handleNameChange} />
                    </div>
                    <div>
                    <label for='name'>Country Origin:</label>
                    <input type='text' value={this.state.origin} onChange={this.handleOriginChange} />
                    </div>
                    <div>
                    <label for='name'>Chef Name:</label>
                    <input type='text' value={this.state.chef_name} onChange={this.handleChefChange} />
                    </div>
                    <div>
                    <label for='name'>Ingredients:</label>
                    <textarea value={this.state.ingredients} onChange={this.handleIngChange} />
                    </div>
                    <input value='submit' type='submit'/>
                </form>
            </div>
        )
    }


 


}

export default RecipeInput

我还对 postRecipe 操作进行了必要的更改

export const postRecipes = (recipe)=>{
    const BASE_URL = `http://localhost:10524`
    const RECIPES_URL =`${BASE_URL}/recipes`

    
    const config = {
        method: "POST",
        body:JSON.stringify(recipe),
        headers: {
        "Accept": "application/json",
        "Content-type": "application/json"
     }
    }
    //category field
    return(dispatch)=>{
    fetch(RECIPES_URL,config)
    .then(response => 
    response.json())
    .then(resp => {
        dispatch({
            type: 'Add_Recipe',
            payload:{
              recipe:{  <-----I encapsulated everything within a recipe value and recipe as my key
                category:resp.category,
                name: resp.name,
                ingredients: resp.ingredients,
                chef_name: resp.chef_name,
                origin: resp.origin,
                // categoryId: resp.categoryId 
                }
            }
        })
    })
    //.then(response => <Recipe />)
      .catch((error) => console.log.error(error))

    }
    
    
}

进行这些更改后,我的 Categories 组件中开始出现 TypeError: Categories is undefined 错误。

import React, { Component } from 'react'

class Categories extends Component{
    

    render(){
        let categories = this.props.category
        //I am getting screamed at for categories being undefined after previous changes
        let optionItems = categories.map((cat,index) =>
            <option key={index}>{cat.category}</option>
        )


        return (
            <div>
                <select>
                    {optionItems}
                </select>
            </div>
        )
    }
}

export default Categories

在将所有内容封装为配方作为我的键并将所有其他属性封装为值之后,类型错误开始发生。有人可以帮助指出我在进行更改后的突破点吗?

1 个答案:

答案 0 :(得分:0)

我认为您正在使用未定义的数据更新您的状态:

this.setState({
   category: initialCats
})

您已将 category 属性封装在 recipe 对象中。所以它应该是这样的:

this.setState({
   recipe: {
     ...this.state.recipe,
     category: initialCats,
   }
})

在您的 Categories 组件返回中,您也可以执行此操作,例如显示正在加载的类别:

return (
            <div>
                <select>
                    {this.props.category.length ? optionItems : <p>Loading...</p>}
                </select>
            </div>
        )