使用useState挂钩更新对象

问题描述

您好,我试图将状态从表单传递到父组件中的const Demo = () => { const onFinish = (values) => { console.log("Success:",values); //Can directly call props here }; const onFinishFailed = (errorInfo) => { console.log("Failed:",errorInfo); }; return ( <Form {...layout} name="basic" initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item label="Title" name="title"> <Input name="title" placeholder="Enter a Title" /> </Form.Item> <Form.Item label="Content" name="content"> <Input name="content" placeholder="Enter the content of the announcement here" /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); }; 钩子,但是提交表单时什么也没有发生。目的是当用户输入高度宽度和颜色时在屏幕上创建一个盒子的视觉效果。

表单代码:

useState

我正在将来自表单的输入通过属性const NewBoxForm = (props) => { const [height,setHeight] = useState(); const [width,setWidth] = useState(); const [color,setColor] = useState(""); const handleChange = (event) => { const {value,name } = event.target; let change = name === "height" ? setHeight(value) : name === "width" ? setWidth(value) : setColor(value); }; const handleSubmit = (event) => { event.preventDefault(); props.createBox(height,width,color); }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="height">Height</label> <input name="height" id="height"type="text" onChange={handleChange} value= {height}> </input> <label htmlFor="width">Width</label> <input name="width" id="width" type="text"onChange={handleChange} value={width}> </input> <label htmlFor="color">Color</label> <input name="color" id="color"type="text" onChange={handleChange} value={color}> </input> </div> <button>Submit</button> </form> ); }; 传递给函数props.createBox,该函数应该更新create状态useState,但不会。当我boxes console.log时,它仅返回newBox ...有人可以看到原因吗?

height

解决方法

const create = (height,width,color) => {
    let newBox = {height: height,width: width,color: color};
    console.log(newBox);
    setBoxes(boxes => [...boxes,newBox])
};
,

您将在handleSubmit调用中发送三个单独的变量,而不是一个对象。

const handleSubmit = (event) => {
    event.preventDefault();
    props.createBox(height,color);
 };

应为:

const handleSubmit = (event) => {
    event.preventDefault();
    props.createBox({height,color});
 };

console.log仅记录高度,因为这是您要发送的第一个参数。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...