反应类型错误:postCompany 不是函数

时间:2021-04-27 10:01:21

标签: javascript reactjs react-router axios react-hooks

我正在制作一个项目,其中我必须在数据库中添加一家新公司。为此,我创建了一个名为“CreateCompany”的导出默认功能组件。实体公司拥有自己的GlobalStateGlobalReducer。因此,Company 的所有 CRUD 函数都存在于 GlobalProviderGlobalProvider em>全局状态

因此,我运行该应用程序,在 CreateCompany 组件中输入数据,该组件是一种接受用户输入并使用状态将信息存储在对象中的表单,然后将该对象传递到 GlobalProvider 中的 postCompany( ) 并显示如下错误:

TypeError: postCompany is not a function

onCompanySubmit
D:/Documents/Code/Al Fayda Al Wataniya/Daybook/server/client/src/components/Company/createCompany.js:24
  21 |            name
  22 |        }
  23 |        // console.log(newCompany)
> 24 |        postCompany(newCompany)
     | ^  25 |    }
  26 | 
  27 |    return (

我还添加了使用相同代码创建新用户的功能,该功能有效,但无效。

创建公司组件代码:

import React, { useState, useContext } from 'react'
import { GlobalContext } from '../../context/Company/CompanyGlobalState'
import '../../App.css'

export default function CreateCompany() {
    const [phone, setPhone] = useState('')
    const [email, setEmail] = useState('')
    const [address, setAddress] = useState('')
    const [poBox, setPOBox] = useState('')
    const [name, setName] = useState('')

    const { postCompany } = useContext(GlobalContext)

    const onCompanySubmit = e => {
        e.preventDefault()
        const newCompany = {
            phone,
            email,
            address,
            poBox,
            name
        }
        // This is the call to the function that will insert new data in the database.
        // The code works till here. The issue lies in the fact that when postCompany() is called,
        // it is not considered a function.
        postCompany(newCompany)
    }

CompanyGlobalState:

import React, { createContext, useReducer } from 'react'
import axios from 'axios'
import CompanyReducer from './CompanyReducer'

// Initial State
const initialState = {
    companies: [],
    error: null,
    loading: true
}

// Create Context
export const GlobalContext = createContext(initialState)

// Provider
export const GlobalProvider = ({ children }) => {
    const [state, dispatch] = useReducer(CompanyReducer, initialState)

    // Actions
    // This is where the problem lies, the compiler doesn't even enter the function
    // The error "TypeError: postCompany is not a function" is given
    async function postCompany(company) {
        console.log(company)
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        }

        try {
            const res = await axios.post('/companies', company, config)
            dispatch({
                type: 'CREATE_COMPANY',
                payload: res.data.data
            })
        } catch (error) {
            dispatch({
                type: 'COMPANY_ERROR',
                payload: error.response.data.error
            })   
        }
        
    }

    return(<GlobalContext.Provider value={{
        companies: state.companies,
        error: state.error,
        loading: state.loading,
        getCompanies,
        deleteCompany,
        postCompany
    }}>
        {children}
    </GlobalContext.Provider>)
}

我使用 axios 进行前端和后端之间的通信。我很困惑,对 React 没有太多经验。请帮助我理解这一点。

2 个答案:

答案 0 :(得分:1)

GlobalProvider 需要在其上方有 <GlobalProvider> <CreateCompany/> </GlobalProvider>

树上的某个地方。

func(df, w=3, l=0, d=1):

它显然不需要像上面那样立即嵌套,它可以是grand-grand-grand-grand-grandchildren 或其他任何东西。

https://reactjs.org/docs/context.html

答案 1 :(得分:0)

感谢@JohnSmith,我想通了。由于我有多个全局状态,每个状态都针对不同的实体,即 Company 的不同全局状态,User 的不同全局状态等,我忘记将这些包含在 App.js 文件中.再次感谢@JohnSmith 帮助我解决这个问题。现在剩下的唯一问题是如何在单个 App.js 文件中使用多个全局提供程序。如果有人对此有想法,请向我推荐。