Javascript 如何在使用上下文api时不在react js中使用匹配道具

Javascript 如何在使用上下文api时不在react js中使用匹配道具,javascript,reactjs,react-hooks,fetch,context-api,Javascript,Reactjs,React Hooks,Fetch,Context Api,我正在创建一个基本的应用程序,我为所有组件使用了上下文api、fetch、react钩子,上下文api组件除外,因为我还在学习使用钩子 我从后端获取数据,我想使用一个组件来创建和更新我的数据,我的主要问题是我不知道如何使用contextApi提供程序中的match prop来使用参数获取editform和singleItem的id。我创建了一个调用singleItem的函数,并将其传递给我的表单组件,因此它可以作为编辑时的初始值,但它不起作用。我收到一个错误未处理的拒绝(TypeError):无

我正在创建一个基本的应用程序,我为所有组件使用了上下文api、fetch、react钩子,上下文api组件除外,因为我还在学习使用钩子

我从后端获取数据,我想使用一个组件来创建和更新我的数据,我的主要问题是我不知道如何使用contextApi提供程序中的match prop来使用参数获取editform和singleItem的id。我创建了一个调用singleItem的函数,并将其传递给我的表单组件,因此它可以作为编辑时的初始值,但它不起作用。我收到一个错误
未处理的拒绝(TypeError):无法读取未定义的属性“params”

我的上下文api组件

import React, { Component, createContext } from 'react'

export const ContactContext = createContext()

export class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default ContactContextProvider

import React, { Component, createContext } from 'react'
import { withRouter } from "react-router";

export const ContactContext = createContext()

class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default withRouter(ContactContextProvider)

import React,{Component,createContext}来自“React”
export const ContactContext=createContext()
导出类ContactContextProvider扩展组件{
状态={
联系人:[],
singleContact:{}
}
componentDidMount(){
取('http://127.0.0.1:5000/Contact')
.then(res=>res.json())
。然后(数据=>{
这是我的国家({
联系人:数据
})
})
this.getSingleItem()
}
getSingleItem=async()=>{
const fetch_id=等待获取(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
const data=wait fetch_id.json()
this.setState({singleContact:data})
}
createContact=(项目)=>{
常数要求={
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify(项目)
}
取('http://127.0.0.1:5000/Contact/add,req)
.then(res=>res.json())
.然后(数据=>数据)
}
编辑联系人=(项目)=>{
常数要求={
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify(项目)
}
取回(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
.then(res=>res.json())
.then(数据=>console.log(数据))
}
deleteContact=(\u id)=>{
取回(`http://127.0.0.1:5000/Contact/${u id}`,{方法:'DELETE'})
.then(res=>res.json())
.then(数据=>console.log(数据))
这是我的国家({
联系人:[…this.state.Contact.filter(项目=>item.\u id!=\u id)]
})
}
render(){
返回(
{this.props.children}
)
}
}
导出默认ContactContextProvider
这是我创建和编辑数据的表单


import { Form, Button, Col} from 'react-bootstrap';
import React, {useState, useContext} from 'react'
import { ContactContext } from '../context/ContactContext';

function Contactform() {
  const {createContact, singleContact, editContact} = useContext(ContactContext)

  const [Contact, setContact] = useState({
    firstName: singleContact.firstName || '',
    lastName: singleContact.lastName || '',
    company: singleContact.company || '',
    phone: singleContact.phone || '',
    email: singleContact.email || '',
    note: singleContact.note || ''
  

  })
  
  const handleChange = (e) =>{
    setContact((prevState)=>({
      ...prevState,
      [e.target.name]:e.target.value
    }))
  }

  const handleSubmit = (e) =>{
    e.preventDefault()
    const item = {
      firstName: Contact.firstName,
      lastName: Contact.lastName,
      company: Contact.company,
      phone: Contact.phone,
      email: Contact.email,
      note: Contact.note
     
      
    }

    if(Contact===''){
      createContact(item)
    }
     else {
       editContact(item)
     }
  }
  
  return (
    
    <Form id='form' onSubmit={handleSubmit} >
      <Form.Row>
    <Form.Group as={Col} >
      <Form.Label>First Name</Form.Label>
      <Form.Control name='firstName' value={Contact.firstName} onChange={handleChange} type="text" placeholder="First Name" />
    </Form.Group>
    <Form.Group as={Col} >
      <Form.Label>Last Name</Form.Label>
      <Form.Control name='lastName' value={Contact.lastName} onChange={handleChange} type="text" placeholder="Last Name" />
    </Form.Group>
    </Form.Row>
    <Form.Row>
    <Form.Group as={Col} >
      <Form.Label>Company</Form.Label>
      <Form.Control name='company' value={Contact.company} onChange={handleChange} type="text" placeholder="Company" />
    </Form.Group>
    <Form.Group as={Col} >
      <Form.Label>Phone</Form.Label>
      <Form.Control name='phone' value={Contact.phone} onChange={handleChange} type="text" placeholder="Phone" />
    </Form.Group>
    </Form.Row>
    <Form.Row>
    <Form.Group as={Col} >
      <Form.Label>Email</Form.Label>
      <Form.Control name='email' type="email" value={Contact.email} placeholder=" email" onChange={handleChange} />
    </Form.Group>
   
    </Form.Row>
   
   
    <Form.Group >
      <Form.Label>Note</Form.Label>
      <Form.Control as="textarea" name='note' value={Contact.note} onChange={handleChange}  rows={3} placeholder='Note'/>
    </Form.Group>
    
    
    <Button  id='form_btn' variant="primary"  type="submit">
      Submit
    </Button>
  </Form>
    )

  
}

export default Contactform

从“react bootstrap”导入{Form,Button,Col};
从“React”导入React,{useState,useContext}
从“../context/ContactContext”导入{ContactContext};
函数Contactform(){
const{createContact,singleContact,editContact}=useContext(ContactContext)
const[Contact,setContact]=useState({
名字:singleContact.firstName | |“”,
lastName:singleContact.lastName | |“”,
公司:singleContact.company | |“”,
电话:singleContact.phone | |“”,
电子邮件:singleContact.email | |“”,
注:singleContact.note | |“
})
常数handleChange=(e)=>{
setContact((prevState)=>({
…国家,
[e.target.name]:e.target.value
}))
}
常量handleSubmit=(e)=>{
e、 预防默认值()
常数项={
名字:Contact.firstName,
lastName:Contact.lastName,
公司:Contact.company,
电话:Contact.phone,
电子邮件:Contact.email,
注:Contact.note
}
如果(联系方式==''){
createContact(项目)
}
否则{
编辑联系人(项目)
}
}
返回(
名字
姓
单位
电话
电子邮件
注
提交
)
}
导出默认联系人表单

您可以简单地执行此操作。我假设您已经在使用
react路由器
。 您只需将
与路由器一起使用
hoc即可。它将通过所有路由器道具

//您的上下文api组件

import React, { Component, createContext } from 'react'

export const ContactContext = createContext()

export class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default ContactContextProvider

import React, { Component, createContext } from 'react'
import { withRouter } from "react-router";

export const ContactContext = createContext()

class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default withRouter(ContactContextProvider)

import React,{Component,createContext}来自“React”
从“react router”导入{withRouter};
export const ContactContext=createContext()
类ContactContextProvider扩展组件{
状态={
联系人:[],
singleContact:{}
}
componentDidMount(){
取('http://127.0.0.1:5000/Contact')
.then(res=>res.json())
。然后(数据=>{
这是我的国家({
联系人:数据
})
})
this.getSingleItem()
}
getSingleItem=async()=>{
const fetch_id=等待获取(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
const data=wait fetch_id.json()
this.setState({singleContact:data})
}
createContact=(项目)=>{
常数要求={
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify(项目)
}
取('http://127.0.0.1:5000/Contact/add,req)
.then(res=>res.json())
.然后(数据=>数据)
}
编辑联系人=(项目)=>{
常数要求={
方法:“POST”,
标题:{'Content-Type':'application/json'},
正文:JSON.stringify(项目)
}
取回(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
.then(res=>res.json())
.then(数据=>console.log(数据))
}
deleteContact=(\u id)=>{
取回(`http://127.0.0.1:5000/Contact/${u id}`,{方法:'DELETE'})
.then(res=>res.json())
.then(数据=>console.log(数据))
这是我的国家({
联系人:[…this.state.Contact.filter(项目=>item.\u id!=\u id)]
})
}
render(){
返回(
{this.props.children}
)
}
}
使用路由器导出默认值(ContactContextProvider)

您可以简单地执行此操作。我假设您已经在使用
react路由器
。 您只需将
与路由器一起使用
hoc即可。它将通过所有路由器道具

//您的上下文api组件

import React, { Component, createContext } from 'react'

export const ContactContext = createContext()

export class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default ContactContextProvider

import React, { Component, createContext } from 'react'
import { withRouter } from "react-router";

export const ContactContext = createContext()

class ContactContextProvider extends Component {

  state = {
    Contact : [],

    singleContact:{}

  }

  componentDidMount(){
    fetch('http://127.0.0.1:5000/Contact')
    .then(res=>res.json())
    .then(data=>{
      this.setState({
        Contact:data
      })
      
    })

    this.getSingleItem()
    
  }

  getSingleItem = async() => {
    const fetch_id = await fetch(`http://127.0.0.1:5000/Contact/${this.props.match.params.id}`)
    const data = await fetch_id.json()

    this.setState({singleContact:data})

  }

  createContact = (item) =>{
    const req = {
      method : 'POST',
      headers : {'Content-Type':'application/json'},
      body: JSON.stringify(item)
    }
    fetch('http://127.0.0.1:5000/Contact/add', req)
    .then(res=>res.json())
    .then(data=> data)
  }

  editContact = (item) => {
    const req = {
      method : 'POST',
      headers : {'Content-Type' : 'application/json'},
      body : JSON.stringify(item)
    }
    fetch(`http://127.0.0.1:5000/Contact/edit/${this.props.match.params.id}`)
    .then(res=>res.json())
    .then(data=>console.log(data))
  }
  
  deleteContact =  (_id) => {
    fetch(`http://127.0.0.1:5000/Contact/${_id}`, {method:'DELETE'})
    .then(res=>res.json())
    .then(data=>console.log(data))
   

    this.setState({
      Contact : [...this.state.Contact.filter(item => item._id !== _id)]
    })
  }

  

  render() {
    return (
      <ContactContext.Provider value={{...this.state, createContact:this.createContact, editContact:this.editContact, deleteContact:this.deleteContact}}>
        {this.props.children}
      </ContactContext.Provider>
    )
  }
}

export default withRouter(ContactContextProvider)

import-React,{Component,createContext}