【问题标题】:React TypeError: postCompany is not a functionReact TypeError:postCompany 不是函数
【发布时间】:2021-07-20 16:05:05
【问题描述】:

我正在做一个项目,我必须在数据库中添加一家新公司。为此,我创建了一个名为“CreateCompany”的导出默认功能组件。实体公司有自己的GlobalStateGlobalReducer。因此,Company 的所有 CRUD 函数都存在于 GlobalProvider 中的 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 (

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

CreateCompany 组件代码:

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)
    }

公司全球州:

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 没有太多经验。请帮助我理解这一点。

【问题讨论】:

  • 试试const tmp = useContext(GlobalContext);,然后是console.log(tmp);,你看到了什么?
  • 如其所言,postCompany 不是函数。你可能没有用GlobalProvider 包裹CreateCompany。尝试记录const globalContext = useContext(GlobalContext); console.log(globalContext); 看看它会产生什么,它可能会记录initialSate
  • @JohnSmith 我试过你说的,你是对的,它给出了initialState。我该如何解决这个问题,你能指导我吗?

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


【解决方案1】:

CreateCompany 上方需要有GlobalProvider

树上的某个地方。

<GlobalProvider>
     <CreateCompany/>
</GlobalProvider>

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 最明显的解决方案是使用不同的上下文。 UserContextCompanyContext 等等。包罗万象的“全局”上下文是个坏主意。
    猜你喜欢
    • 2016-09-02
    • 2018-12-23
    • 2023-03-27
    • 2020-09-11
    • 2016-11-21
    • 2020-12-04
    • 2021-07-11
    • 2015-09-01
    • 2015-08-22
    相关资源
    最近更新 更多