Javascript 如何在react钩子中创建新的JSON对象?

Javascript 如何在react钩子中创建新的JSON对象?,javascript,html,json,reactjs,react-hooks,Javascript,Html,Json,Reactjs,React Hooks,我有两个问题:首先,如何在钩子中添加/更新JSON项? 另一个React不允许我使用以前JSON文件中存储的名称 基本上,我对其他解决方案持开放态度,因为我的输入字段是从JSON文件动态生成的。我不确定存储或访问输入数据的最佳方式。我认为将它们作为JSON存储在react钩子中,然后作为道具传递给另一个组件可能是最好的 我想做的是onChange,我希望quantity值作为一个JSON对象存储在一个钩子中这是我的代码: 反应: import React, { useState, useEffe

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

基本上,我对其他解决方案持开放态度,因为我的输入字段是从JSON文件动态生成的。我不确定存储或访问输入数据的最佳方式。我认为将它们作为JSON存储在react钩子中,然后作为道具传递给另一个组件可能是最好的

我想做的是onChange,我希望quantity值作为一个JSON对象存储在一个钩子中这是我的代码:

反应:

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 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",
    }
]

假设你的
数量
对象看起来像:

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

在React中更新状态时,替换对象而不是修改现有对象是很重要的,因为这会告诉React重新渲染组件。这通常通过使用扩展运算符和数组函数(如
map
filter
)来实现。例如:

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
null ?? 'hello'; // resolves to "hello"
undefined ?? 'world'; // resolves to "world"
"foo" ?? "bar"; // resolves to "foo"
请注意,“排列”操作符在第一级以下不进行操作,我的意思是,对象中的对象将通过引用进行复制,例如:

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
null ?? 'hello'; // resolves to "hello"
undefined ?? 'world'; // resolves to "world"
"foo" ?? "bar"; // resolves to "foo"
同样在我的回答中,我使用了空合并运算符(
??
),如果左操作数为
null
未定义
,这将返回其右操作数,例如:

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
null ?? 'hello'; // resolves to "hello"
undefined ?? 'world'; // resolves to "world"
"foo" ?? "bar"; // resolves to "foo"
在我的回答中,如果
Quantities[components.Name]
未定义,我使用它回退到一个空对象

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

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

你介意给我一个快速的解释/代码分解以便我完全理解吗?我已经添加了一些对所用代码的解释,希望对你有所帮助。