【问题标题】:React Hooks: Set All State Values to the Same Values with useStateReact Hooks:使用 useState 将所有状态值设置为相同的值
【发布时间】:2021-02-12 01:25:46
【问题描述】:

React 新手。我试图弄清楚如何将所有对象的状态值设置为一个特定对象的值。

这里是 CodeSandbox:https://codesandbox.io/s/blissful-https-1o415

如果您单击Fork 部分中的Apply to All 按钮,SpoonKnife 中的数据将更新为与Fork 部分中的数据相同。是否可以将地图中一个对象的数据与另一个对象的数据一起设置?它会发生在地图功能还是其他地方?提前感谢您的帮助。

import React, { useState, useEffect } from "react";
import axios from "axios";
import "./styles.css";

function App() {
  const [kitchenItems, setkitchenItems] = useState([]);

  useEffect(() => {
    axios
      .get("./data.json")
      .then((response) => setkitchenItems(response.data.kitchen));
  }, []);

  function applyAll(i) {
    const updatedData = kitchenItems.map((item, idx) => {
      if (idx === i) {
        return {
          ...item,
          size: item.size,
          text: item.text,
          value: item.value
        };
      }
      return item;
    });
    setkitchenItems(updatedData);
    console.log(kitchenItems);
  }

  return (
    <main>
      {kitchenItems.map((item, i) => (
        <div className="utensil" key={i}>
          <h2>{item.name}</h2>
          <ul>
            <li>{item.size}</li>
            <li>{item.text}</li>
            <li>{item.value}</li>
          </ul>
          <button type="button" name="apply" onClick={() => applyAll(i)}>
            Apply to All
          </button>
        </div>
      ))}
    </main>
  );
}

export default App;

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    如另一个答案中所述,您将看不到控制台日志的更新,因为它是异步的,您需要使用 useEffect 来查看更新。不过,您的代码很接近。几件事:

    1. 你需要为 applyAll 使用一个稳定的函数(useCallback hook)

    2. 您正在查看与您尝试复制的对象相等的索引,并且只是使用相同的值。这只是将勺子变成了已经勺子,因为它的大小和更多值。你想要的是改变其他人。这是我在您的 codepen 上制作的示例:

    import React, { useCallback, useEffect, useState } from "react";
    import axios from "axios";
    import "./styles.css";
    
    function App() {
      const [kitchenItems, setkitchenItems] = useState([]);
    
      useEffect(() => {
        axios
          .get("./data.json")
          .then((response) => setkitchenItems(response.data.kitchen));
      }, []);
    
      const applyAll = useCallback((i) => {
        const updatedData = kitchenItems.map((item, idx) => {
          if (idx !== i) { //<-- You want to check if the index of the item doesn't equal the index of the item you want to change it to.
            return {
              ...item,
              size: kitchenItems[i].size, //<-- Since you have the index of the item, you can just call to get it's values here from kitchenItems
              text: kitchenItems[i].text,
              value: kitchenItems[i].value
            };
          }
          return item;
        });
        setkitchenItems(updatedData);
      }, [kitchenItems]);
    
      return (
        <main>
          {kitchenItems.map((item, i) => (
            <div className="utensil" key={i}>
              <h2>{item.name}</h2>
              <ul>
                <li>{item.size}</li>
                <li>{item.text}</li>
                <li>{item.value}</li>
              </ul>
              <button type="button" name="apply" onClick={() => applyAll(i)}>
                Apply to All
              </button>
            </div>
          ))}
        </main>
      );
    }
    
    export default App;
    

    如果我了解您要完成的工作,这应该可以解决您的问题。

    【讨论】:

      【解决方案2】:

      setkitchenItems()是异步方法,不能在setkitchenItems()之后立即获取kitchenItems的更新值。

          setkitchenItems(updatedData);
          console.log(kitchenItems); // This will console the old `kitchenItems`
      

      您应该使用 useEffect 并添加 kitchenItems 依赖项来检查更新的状态值。

      useEffect(() => {
        console.log(kitchenItems);
      }, [kitchenItems]);
      

      【讨论】:

      • 好的,谢谢!我已经更新了 CodeSanbox。我想弄清楚的是,我是否可以将 kitchenitems 中所有对象的值设置为我单击的 kitchenItem 的值。
      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 2020-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多