我是React Hooks的新手。我有一个UI,其中有多个输入,对象中有值。我使用循环创建了UI,因此我想使用一个回调来更新输入。
“商店”输入使用其自己的回调并成功更新状态。但是“产品”输入永远不会更新状态。我真的不明白为什么这两个回调的行为会有所不同。
代码在下面。问题出在handleChange
回调中。
import React, { useCallback, useState, useEffect } from "react";
import { TextField, Form } from "@shopify/polaris";
export default function TextFieldExample() {
const [values, setValues] = useState({
"prod-0": "Jaded Pixel",
"prod-1": "blue diamonds"
});
const [shop, setShop] = useState("Joe's house of pancakes");
const handleChangeShop = useCallback(newName => {
setShop(newName);
}, []);
const handleChange = useCallback((newValue, id) => {
console.log("Pre: values:", values);
console.log(id, newValue);
const newProds = values;
newProds[id] = newValue;
setValues(newProds);
console.log("Post: newProds:", newProds);
}, [values]);
useEffect(() => { // observing if State changes
console.log("in useEffect: shop:", shop); // this gets called and is updated when changed.
console.log("in useEffect: values:", values); // this never gets called or updated.
}, [values, shop]);
const items = [];
Object.keys(values).forEach(function(prod) {
items.push(
<TextField label={"Product " + prod.substr(5)} id={prod} value={values[prod]} onChange={handleChange} />
);
});
return (
<Form>
<TextField label="Shop" id="shop" value={shop} onChange={handleChangeShop}/>
{items}
</Form>
);
}
代码沙箱位于此处:https://codesandbox.io/s/fast-tdd-1ip38
试试看,看看控制台。
答案 0 :(得分:3)
您正在更改values
状态,请参见this沙箱
将您的handleChange
函数更改为
const handleChange = useCallback((newValue, id) => {
const newProds = { ...values };
newProds[id] = newValue;
setValues(newProds);
}, [values]);
您可以将其进一步更改为
const handleChange = useCallback((newValue, id) => {
setValues(prods => ({...prods, [id] : newValue }));
}, [values]);
答案 1 :(得分:2)
尝试将handleChange
更新为此:
const handleChange = useCallback(
(newValue, id) => {
console.log("Pre: values:", values);
console.log(id, newValue);
setValues(state => ({ ...state, [id]: newValue}));
},
[values]
);