布尔值不保存到状态使用 react-redux

问题描述

我正在构建一个电子商务网站,并且正在添加管理功能来编辑当前用户。我的 isSeller 和 isAdmin 变量的认值设置为 false。当我尝试将其更改为 true 时,它​​工作正常,但我无法将其更改回 false。我试过将认值更改为 true 并创建一个新用户并将其更改为 false,但这也不起作用。这是我的一些代码https://github.com/amkreiner/buyitallonline

用户编辑屏幕

export default function UserEditScreen(props) {
  const userId = props.match.params.id;
  const [name,setName] = useState("");
  const [email,setEmail] = useState("");
  const [isSeller,setIsSeller] = useState(false);
  const [isAdmin,setIsAdmin] = useState(false);

  const userDetails = useSelector((state) => state.userDetails);
  const { loading,error,user } = userDetails;

  const userUpdate = useSelector((state) => state.userUpdate);
  const {
    loading: loadingUpdate,error: errorUpdate,success: successUpdate,} = userUpdate;

  const stringToBoolean = (value) => {
    console.log(value);
    if (value && typeof value === "string") {
      if (value.toLowerCase() === "yes") return true;
      if (value.toLowerCase() === "no") return false;
    }
    return value;
  };

  const changeValue = (value) => {
    if (value === true) {
      return "yes";
    }
    if (value === false) {
      return "no";
    }
    return value;
  };

  const dispatch = usedispatch();

  useEffect(() => {
    if (successUpdate) {
      dispatch({ type: USER_UPDATE_RESET });
      props.history.push("/userlist");
    }
    if (!user) {
      dispatch(detailsUser(userId));
    } else {
      setName(user.name);
      setEmail(user.email);
      setIsSeller(user.isSeller);
      setIsAdmin(user.isAdmin);
    }
  },[dispatch,props.history,successUpdate,user,userId]);


  const submitHandler = (e) => {
    e.preventDefault();
    //dispatch update user
    console.log(`isSeller:${isSeller}`);
    console.log(`isAdmin:${isAdmin}`);
    dispatch(updateUser({ _id: userId,name,email,isSeller,isAdmin }));
  };

...

    <div>
      <label htmlFor="isSeller">Is Seller</label>
      <select
        onChange={(e) => setIsSeller(stringToBoolean(e.target.value))}
        id="isSeller"
        value={changeValue(isSeller)}
      >
        <option value="yes">Yes</option>
        <option value="no">No</option>
      </select>
    </div>
    <div>
      <label htmlFor="isAdmin">Is Admin</label>
      <select
        onChange={(e) => setIsAdmin(stringToBoolean(e.target.value))}
        id="isAdmin"
        value={changeValue(isAdmin)}
      >
        <option value="yes">Yes</option>
        <option value="no">No</option>
      </select>
    </div>

减速器

export const userUpdateReducer = (state = {},action) => {
  switch (action.type) {
    case USER_UPDATE_REQUEST:
      return { loading: true };
    case USER_UPDATE_SUCCESS:
      return { loading: false,success: true };
    case USER_UPDATE_FAIL:
      return { loading: false,error: action.payload };
    case USER_UPDATE_RESET:
      return {};
    default:
      return state;
  }
};

用户操作

export const updateUser = (user) => async (dispatch,getState) => {
  dispatch({ type: USER_UPDATE_REQUEST,payload: user });
  const {
    userSignin: { userInfo },} = getState();
  try {
    const { data } = await Axios.put(`/api/users/${user._id}`,{
      headers: { Authorization: `Bearer ${userInfo.token}` },});
    dispatch({ type: USER_UPDATE_SUCCESS,payload: data });
  } catch (error) {
    const message =
      error.response && error.response.data.message
        ? error.response.data.message
        : error.message;
    dispatch({ type: USER_UPDATE_FAIL,payload: message });
  }
};

型号

import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {
    name: { type: String,required: true },email: { type: String,required: true,unique: true },password: { type: String,isAdmin: { type: Boolean,default: false,isSeller: { type: Boolean,},{
    timestamps: true,}
);
const User = mongoose.model("User",userSchema);
export default User;

路由器

userRouter.put(
  "/:id",isAuth,isAdmin,expressAsyncHandler(async (req,res) => {
    const user = await User.findById(req.params.id);
    if (user) {
      user.name = req.body.name || user.name;
      user.email = req.body.email || user.email;
      user.isSeller = req.body.isSeller || user.isSeller;
      user.isAdmin = req.body.isAdmin || user.isAdmin;
      const updatedUser = await user.save();
      res.send({ message: "User Updated",user: updatedUser });
    } else {
      res.status(404).send({ message: "User Not Found" });
    }
  })
);

如果您需要其他任何东西,可以在 https://github.com/amkreiner/buyitallonline

找到我更新的存储库

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)