【问题标题】:react redux- updating statereact redux - 更新状态
【发布时间】: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;

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您以错误的方式更新状态。您仅用新的有效负载替换状态。您需要做的是保留以前的状态数据,然后添加新的有效载荷。

    switch (action.type) {
      .....
      case UPDATE_USER:
        return { ...state, users: [...state.users, action.payload] };
      default:
        return state;
      }
    };
    

    【讨论】:

    • 能否请您 console.log 状态以及输出是什么。 state.users 根据您的实现应该是一个数组。您收到此错误是因为 state.users 显示为对象。
    • 为了添加到 Nedzny 的 cmets,当你不需要的时候,你也在解构状态。你有这行:const{ users} = useSelector((state)=>state.users) 当它真的应该是:const users = useSelector(state => state.users) 这是我对你的错误的猜测
    • state.users 的控制台.log。也改变 const users = useSelector(state => state.users) 没有改变任何东西i.stack.imgur.com/DOKTN.png
    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2020-08-07
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多