【问题标题】:How do I create a new JSON object inside a react hook?如何在反应钩子中创建一个新的 JSON 对象?
【发布时间】:2021-03-16 11:54:31
【问题描述】:

首先我有两个问题,如何在挂钩中添加/更新 JSON 项目? 另一个是 React 不允许我使用从以前的 JSON 文件中存储的名称。

基本上,我对其他解决方案持开放态度,因为我的输入字段是从 JSON 文件动态生成的JSON,然后将它们作为道具传递给另一个组件可能是最好的。

我想要发生的是 onChange 我希望将数量值作为 JSON 对象存储在 Hook 中这是我的代码:

反应:

import React, { useState, useEffect } from 'react';
import Data from '../shoppingData/Ingredients';
import Quantities from '../shoppingData/Quantities';

const ShoppingPageOne = (props) => {
  //element displays
  const [pageone_show, setPageone_show] = useState('pageOne');

  //where I want to store the JSON data
  const [Quantities, setQuantities] = useState({});

  useEffect(() => {
    //sets info text using Json
    if (props.showOne) {
      setPageone_show('pageOne');
    } else {
      setPageone_show('pageOne hide');
    }
  }, [props.showOne]);

  return (
    <div className={'Shopping_Content ' + pageone_show}>
      //generates input fields from JSON data
      {Data.map((Ingredients) => {
        const handleChange = (event) => {
          // this is where I'd like the Hook to be updated to contain instances of the ingredients name and quantity of each
          setQuantities(
            (Ingredients.Name: { ['quantities']: event.target.value })
          );

          console.log(Quantities);
        };

        return (
          <div className="Shopping_input" key={Ingredients.Name}>
            <p>
              {Ingredients.Name} £{Ingredients.Price}
            </p>
            <input
              onChange={handleChange.bind(this)}
              min="0"
              type="number"
            ></input>
          </div>
        );
      })}
      <div className="Shopping_Buttons">
        <p onClick={props.next_ClickHandler}>Buy Now!</p>
      </div>
    </div>
  );
};

export default ShoppingPageOne;

JSON 文件:

//Json data for the shopping ingredients

export default [
    {
        Name: 'Bread',
        Price: "1.10",
    },

    {
        Name: 'Milk',
        Price: "0.50",
    },

    {
        Name: 'Cheese',
        Price: "0.90",
    },

    {
        Name: 'Soup',
        Price: "0.60",
    },

    {
        Name: 'Butter',
        Price: "1.20",
    }
]

【问题讨论】:

    标签: javascript html json reactjs react-hooks


    【解决方案1】:

    假设您的 Quantities 对象看起来像:

    {
        <Ingredient Name>: { quantities: <value> }
    }
    

    您需要将您的 handleChange 更改为如下所示

    const handleChange = (event) => {
        setQuantities({
            ...Quantities,
            [Ingredients.Name]: {
                ...(Quantities[Ingredients.Name] ?? {}),
                quantities: event.target.value
            }
        });
    };
    

    解释

    在 React 中更新状态时,替换对象而不是改变现有对象很重要,因为这是告诉 React 重新渲染组件的原因。这通常使用扩展运算符以及mapfilter 等数组函数来完成。例如:

    const myObject = { test: 1 };
    myObject.test = 2; // Mutates existing object, wrong!
    const myNewObject = { ...myObject, test: 2 }; // Creates new object, good!
    

    注意扩展运算符在第一级以下不操作,我的意思是对象内的对象将通过引用进行复制,例如:

    const myObject = { test : { nested: 1 } };
    const myObject2 = { ...myObject };
    myObject2.test.nested = 2;
    console.log(myObject.test.nested); // outputs 2
    

    同样在我的回答中,我使用了空值合并运算符 (??),如果左操作数是 nullundefined,这将返回它的右操作数,例如:

    null ?? 'hello'; // resolves to "hello"
    undefined ?? 'world'; // resolves to "world"
    "foo" ?? "bar"; // resolves to "foo"
    

    在我的回答中,如果 Quantities[Ingredients.Name] 未定义,我会使用它回退到一个空对象。

    最后,我在将变量用作对象键时使用了方括号,因为这会导致表达式在用作键之前被评估:

    const myKey = 'hello';
    const myObject = {
        [myKey]: 'world';
    };
    console.log(myObject); // { hello: 'world' }
    

    【讨论】:

    • 您介意快速解释/分解代码以便我完全理解吗?
    • 我已经添加了一些使用的代码的一些解释,希望对你有所帮助。
    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2021-07-18
    • 1970-01-01
    • 2023-01-22
    • 2013-03-01
    • 2021-12-17
    相关资源
    最近更新 更多