有关更新状态和挂钩的问题(可能与打字稿有关)

时间:2019-10-23 22:28:44

标签: reactjs typescript

另一个问题在这里。我确实想出了一个可行的解决方案,但我很好奇要提出一些其他更好的想法。基本上,我想做的是在输入中输入一些颜色并添加到对象数组中。还有与之相关的验证,以防止使用唯一的颜色或颜色名称。

这是我的工作解决方案:

UseState hooks:
--------------------------------------------------------------------------------

const [currentColor, setCurrentColor] = useState("teal");
const [colors, setColors] = useState([{ color: "", name: "" }]);
const [newName, setNewName] = useState("");


useEffect hook for the validation:
--------------------------------------------------------------------------------

useEffect(() => {
        ValidatorForm.addValidationRule("isColorNameUnique", value => {
            return colors.every(({ name }: any) => {
                console.log(name);
                return name.toLowerCase() !== value.toLowerCase();
            });
        });

        ValidatorForm.addValidationRule("isColorUnique", value => {
            return colors.every(({ color }: any) => color !== currentColor);
        });
    });


function that gets called when submitted:
--------------------------------------------------------------------------------

const addNewColor = () => {
        const newColor = {
            color: currentColor,
            name: newName
        };

        if (
            Object.keys(colors[0].color).length === 0 &&
            Object.keys(colors[0].name).length === 0
        ) {
            setColors([newColor]);
        } else {
            setColors([...colors, newColor]);
        }

        setNewName("");
    };

如果我有

const [colors, setColors] = useState([{}]);

const addNewColor = () => {
        const newColor = {
            color: currentColor,
            name: newName
        };

        setColors([...colors, newColor]);

        setNewName("");
    };

验证逻辑给出有关“无法读取未定义的属性名称”的错误,这很有意义。我尝试在验证本身中添加逻辑以防止这种情况的发生,以消除该错误,但仍在数组中添加空对象作为第一个索引。

这种方式也可以

const [colors, setColors] = useState([{color: "", name: ""]);

const addNewColor = () => {
        const newColor = {
            color: currentColor,
            name: newName
        };

        setColors([...colors, newColor]);

        setNewName("");
    };

,但是默认情况下它的第一个索引是空对象,例如 {color:“”,name:“”}并且它永远不会被替换。

如果我这样做

const [colors, setColors] = useState([]);

const addNewColor = () => {
        const newColor = {
            color: currentColor,
            name: newName
        };

        setColors([...colors, newColor]);

        setNewName("");
    };

我收到此错误 https://i.imgur.com/3CCbo7X.png

还有另一种方法可以使它通过验证并在没有用的状态下没有空对象。

谢谢!

1 个答案:

答案 0 :(得分:0)

由于您使用的是打字稿,为什么不介绍颜色的界面

interface IColor {
  color: string,
  name: string,
}

并通过以下操作初始化状态挂钩:

const [colors, setColors] = useState<IColor[]>([]);

然后,将颜色推入数组就像:

const newColor: IColor = {
  color: currentColor,
  name: newName
};

setColors([...colors, newColor]);
相关问题