React Hook useCallback不更新状态值

时间:2020-03-29 07:09:57

标签: reactjs shopify react-hooks

我是React Hooks的新手。我有一个UI,其中有多个输入,对象中有值。我使用循环创建了UI,因此我想使用一个回调来更新输入。

enter image description here

“商店”输入使用其自己的回调并成功更新状态。但是“产品”输入永远不会更新状态。我真的不明白为什么这两个回调的行为会有所不同。

代码在下面。问题出在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
试试看,看看控制台。

2 个答案:

答案 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]
  );