【发布时间】:2021-07-20 16:05:05
【问题描述】:
我正在做一个项目,我必须在数据库中添加一家新公司。为此,我创建了一个名为“CreateCompany”的导出默认功能组件。实体公司有自己的GlobalState和GlobalReducer。因此,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