简体   繁体   English

如何在反应钩子中创建新的 JSON object?

[英]How do I create a new JSON object inside a react hook?

I have two issues first how do I add/update the JSON items within a hook?我首先有两个问题,如何在挂钩中添加/更新 JSON 项目? The other being that React won't let me use the name stored from a previous JSON file.另一个是 React 不允许我使用之前 JSON 文件中存储的名称。

I am open to other solutions, basically, as my input field are dynamically generated from a JSON file I'm unsure of the best way to store or access the data that's input into them I think storing them in a react hook as JSON and then passing them though as props to another component is probably best.基本上,我对其他解决方案持开放态度,因为我的输入字段是从 JSON 文件动态生成的将它们作为道具传递给另一个组件可能是最好的。

What I want to happen is onChange I would like the quantity value to be stored as a JSON object in a Hook here's my code:我想要发生的是 onChange 我希望在 Hook 中将数量值存储为 JSON object 这是我的代码:

React:反应:

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

Assuming your Quantities object is meant to look like:假设您的Quantities object 看起来像:

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

you need to change your handleChange to look like this你需要改变你的handleChange看起来像这样

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

Explanation解释

When updating state in React, it is important to replace objects rather than mutating existing ones, as this is what tells React to rerender components.在 React 中更新 state 时,替换对象而不是改变现有对象很重要,因为这是告诉 React 重新渲染组件的原因。 This is commonly done using the spread operator, and with array functions such as map and filter .这通常使用扩展运算符和数组函数(例如mapfilter )来完成。 For example:例如:

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

Note the spread operator doesn't operate below the first level, what I mean by that is, objects within the object will be copied by reference, for example:注意扩展运算符不会在第一级以下操作,我的意思是,object 中的对象将通过引用复制,例如:

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

Also in my answer, I have used the nullish coalescing operator ( ?? ), this will return it's right operand if the left operand is null or undefined , for example:同样在我的回答中,我使用了空值合并运算符( ?? ),如果左操作数是nullundefined ,这将返回它的右操作数,例如:

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

In my answer I used it to fallback to an empty object if Quantities[Ingredients.Name] is undefined.在我的回答中,如果Quantities[Ingredients.Name]未定义,我用它回退到一个空的 object。

Finally, I used square brackets when using a variable as an object key as this causes the expression to be evaluated before being used as a key:最后,在将变量用作 object 键时,我使用了方括号,因为这会导致表达式在用作键之前被评估:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 object 添加到反应挂钩? - How do I add an object to a react hook? 如何创建与 JSON object 匹配的 React useState 挂钩 - How to create React useState hook matching to JSON object 如何使用 typescript 从 React 中的状态创建新的 object? - How do I create a new object from states in React with typescript? 如何在 React JS 中从 JSON object 创建表? - How do I create a table from a JSON object in React JS? 如何在 React useEffect() 挂钩中链接异步方法 - How do I chain async methods inside React useEffect() hook 我如何创建一个函数来更改位于数组内的对象内的属性,在 JSON 中 - How do i create a function that will change the property inside an object that is located inside of an array, in a JSON 在 React 中获取请求:如何在对象数组中映射对象的 JSON 数组? - Fetch request in React: How do I Map through JSON array of object inside of array of objects? 如何使用 json 数组创建一个新的 object,只有名称-值对和 javascript? - How do I use a json array to create a new object with only name-value pairs with javascript? 如何遍历json对象的嵌套属性并创建新的数组列表? - How do I iterate through nested properties of an json object and create a new array list? 如何在 React js 中创建 json object 文字的唯一数据集? - How do I create an unique dataset of json object literal in React js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM