【发布时间】:2021-11-03 20:44:40
【问题描述】:
我在更新用户状态方面需要帮助。我使用姓名、电子邮件和密码注册了一个用户。然后在个人资料页面中,我想有机会更新(或创建新)值,例如城市和国家。现在我很困惑。我的 Redux 操作
export const updateUser=(profileId, updatedUser)=>async(dispatch)=>{
try {
const {data}= await api.updateUser(profileId,updatedUser)
dispatch({type: UPDATE_USER, payload: data})
} catch (error) {
console.log(error.message);
}
减速机:
const initialState = {
users: [
{
city: "", country: "", email: "", name: "",
password: "",
_id: "",
},
],
};
const user = (state = initialState, action) => {
switch (action.type) {
case GET_ONE_USER:
return {
...state,
users: action.payload,
};
case UPDATE_USER:
return { ...state, users: action.payload };
default:
return state;
}
};
API:
export const updateUser=(profileId, updatedUser)=>API.patch(`/user/${profileId}`, updatedUser)
路线:
router.patch('/:profileId',updateUser)
控制器:
export const updateUser = async (req,res)=>{
const {id} = req.params
const {city, country} = req.body
const updatedUser={city, country}
try {
await User.findByIdAndUpdate(id,updatedUser, {new: true} )
res.status(200).json(updatedUser)
} catch (error) {
res.status(400).json({message: 'Blad'})
}
}
在我的组件中:
const{ users} = useSelector((state)=>state.users)
并提交处理程序const handleSubmit =(e) =>{ e.preventDefault() dispatch(updateUser(users._id, data)) }
当我单击按钮并调度一个动作时,它只会更改新值,所有其他值都会被删除。我认为这与我从减速器返回的状态有关?
编辑: 好的,我以某种方式解决了这个问题,尽管我认为我可以简化代码?
case UPDATE_USER:
return { ...state, users: {...state.users, city:action.payload.city, country:action.payload.country}};
default:
return state;
【问题讨论】: