如何在React钩子内创建一个新的JSON对象? [英] How do I create a new JSON object inside a react hook?

查看:53
本文介绍了如何在React钩子内创建一个新的JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two issues first how do I add/update the JSON items within a hook? The other being that React won't let me use the name stored from a previous JSON file.

基本上,我对其他解决方案持开放态度,因为我的输入字段是根据JSON文件动态生成的,因此我不确定存储或访问输入到其中的数据的最佳方法,我认为将它们存储在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.

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

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:

反应:

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

推荐答案

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

Assuming your Quantities object is meant to look like:

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

您需要更改您的 handleChange 使其看起来像这样

you need to change your handleChange to look like this

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

说明

在React中更新状态时,重要的是替换对象而不是对现有对象进行突变,因为这告诉React重新渲染组件.通常使用散布运算符以及数组功能(例如 map filter )来完成此操作.例如:

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. This is commonly done using the spread operator, and with array functions such as map and filter. 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:

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

在我的回答中,我使用了空的合并运算符( ?? ),如果左侧操作数为 null ,则此操作将返回其右侧操作数未定义,例如:

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:

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

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

In my answer I used it to fallback to an empty object if Quantities[Ingredients.Name] is undefined.

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

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:

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

这篇关于如何在React钩子内创建一个新的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆