如何在使用上下文时在 react js 中使用匹配道具 api
How do t use match props in react js while using context api
我正在创建一个基本的应用程序,我使用了上下文 api、获取、除上下文 api 组件之外的所有组件的反应挂钩,因为我仍在学习使用挂钩。
我从后端获取了我的数据,我想使用一个组件来创建和更新我的数据,我的主要问题是我不知道如何使用 contextApi 提供程序中的 match prop 来获取使用参数的 editform 和 singleItem 的 id。我创建了一个调用 singleItem 的函数,并将它传递给我的表单组件,因此它可以作为编辑时的初始值,但它没有用。我收到一个错误 Unhandled Rejection (TypeError): Cannot read property 'params' of undefined
。
我的上下文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 { 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-router
。
您可以简单地使用 withRouter
hoc。它将传递所有路由器道具。
//你的上下文api组件
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)
我正在创建一个基本的应用程序,我使用了上下文 api、获取、除上下文 api 组件之外的所有组件的反应挂钩,因为我仍在学习使用挂钩。
我从后端获取了我的数据,我想使用一个组件来创建和更新我的数据,我的主要问题是我不知道如何使用 contextApi 提供程序中的 match prop 来获取使用参数的 editform 和 singleItem 的 id。我创建了一个调用 singleItem 的函数,并将它传递给我的表单组件,因此它可以作为编辑时的初始值,但它没有用。我收到一个错误 Unhandled Rejection (TypeError): Cannot read property 'params' of undefined
。
我的上下文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 { 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-router
。
您可以简单地使用 withRouter
hoc。它将传递所有路由器道具。
//你的上下文api组件
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)