所以我用react redux开发了一个联系人应用。在这里,添加和删除功能正常工作。但是在编辑部分有一个问题。当您点击联系人的更新按钮时,您将被引导到该页面,所有信息将被填写在适当的输入中。但是我在更新部分遇到了一个错误。我该如何弥补我的错误?
import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useParams } from 'react-router-dom'
import { UpdateContact } from '../redux/actions/Actions'
const UpdateContactPage = () => {
const { id } = useParams()
const contacts = useSelector(state => state.userReducer.contacts)
const updatedBlog = contacts.find((blog) => blog.id === id)
const [a, setA] = useState(updatedBlog)
const [user, setUser] = useState({
id: a.id,
userName: a.userName,
surname: a.surname,
image: a.image
})
const handleChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value })
}
const dispatch = useDispatch();
const updateContactForm = (e) => {
e.preventDefault()
// dispatch(UpdateContact(user))
console.log(user);
}
return (
<>
<div className="container mt-5">
<form onSubmit={updateContactForm}>
<div className="mb-3">
<input type="text" name='userName' className="form-control" placeholder='username' onChange={handleChange} defaultValue={a.userName} />
</div>
<div className="mb-3">
<input type="text" name='image' className="form-control" placeholder='img' onChange={handleChange} defaultValue={a.image} />
</div>
<div className="mb-3">
<input type="text" name='surname' className="form-control" placeholder='surname' onChange={handleChange} defaultValue={a.surname} />
</div>
<button type="submit" className="btn btn-primary">Update</button>
</form>
</div>
</>
)
}
export default UpdateContactPage
const initialState = {
contacts: localStorage.getItem('Contacts') ? JSON.parse(localStorage.getItem('Contacts')) : []
}
export const AppReducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_CONTACT":
return {
...state,
contacts: [...state.contacts, action.payload]
}
case "UPDATE_CONTACT":
const updatedContact = action.payload;
const updatedContacts = state.contacts.map((contact) => {
if (contact.id === updatedContact.id) {
return updatedContact
}
return contact
})
return updatedContacts
case "REMOVE_CONTACT":
return {
...state,
contacts: state.contacts.filter((item) => item.id !== action.payload)
}
case "REMOVE_ALL_CONTACTS":
return {
...state,
contacts: []
}
default:
return state;
}
}
export const AddContact = (user) => {
return {
type: 'ADD_CONTACT',
payload: user
}
}
export const DeleteContact = (id) => {
return {
type: 'REMOVE_CONTACT',
payload: id
}
}
export const UpdateContact = (id) => {
return {
type: 'UPDATE_CONTACT',
payload: id
}
}
export const RemoveAll = () => {
return {
type: 'REMOVE_ALL_CONTACTS',
}
}
1条答案
按热度按时间ecfsfe2w1#
在reducer的
UPDATE_CONTACT
例子中,你使用的是payload,就好像它是一个用户:但是UpdateContact函数的有效载荷有一个id: