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

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

问题描述

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

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

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

反应:

import React, { useState, useEffect } from 'react';从'../shoppingData/Ingredients'导入数据;从../shoppingData/Quantities"导入数量;const ShoppingPageOne = (道具) =>{//元素显示const [pageone_show, setPageone_show] = useState('pageOne');//我想在哪里存储JSON数据const [Quantities, setQuantities] = useState({});useEffect(() => {//使用Json设置信息文本如果(道具.showOne){setPageone_show('pageOne');} 别的 {setPageone_show('pageOne 隐藏');}}, [props.showOne]);返回 (<div className={'Shopping_Content' + pageone_show}>//从JSON数据生成输入字段{Data.map((成分) => {const handleChange = (事件) =>{//这是我希望更新 Hook 以包含每种成分名称和数量的实例的地方设置数量((Ingredients.Name: { ['quantities']: event.target.value }));控制台日志(数量);};返回 (<div className="Shopping_input";key={Ingredients.Name}><p>{Ingredients.Name} £{Ingredients.Price}</p><输入onChange={handleChange.bind(this)}min=0"类型=数字"></输入>

);})}<div className=Shopping_Buttons"><p onClick={props.next_ClickHandler}>立即购买!</p>

);};导出默认的 ShoppingPageOne;

JSON 文件:

//购物原料的Json数据导出默认值 [{名称: '面包',价格:1.10",},{名称:'牛奶',价格:0.50",},{名称: '奶酪',价格:0.90",},{名称: '汤',价格:0.60",},{名称: '黄油',价格:1.20",}]

解决方案

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

<代码>{<成分名称>:{数量:<价值>}}

你需要把你的handleChange改成这样

const handleChange = (event) =>{设置数量({...数量,[成分.名称]:{...(数量[成分.名称] ?? {}),数量:事件.目标.值}});};

说明

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

const myObject = { test: 1 };myObject.test = 2;//改变现有的对象,错了!const myNewObject = { ...myObject,测试:2 };//创建新对象,很好!

注意spread操作符在第一层以下不会操作,我的意思就是对象内的对象会被引用复制,例如:

const myObject = { test : {nested: 1 } };const myObject2 = { ...myObject };myObject2.test.nested = 2;控制台日志(myObject.test.nested);//输出 2

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

null ??'你好';//解析为hello"不明确的 ??'世界';//解析为world";富"??酒吧";//解析为foo"

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

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

const myKey = 'hello';const myObject = {[myKey]: '世界';};控制台日志(我的对象);//{ 你好世界' }

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.

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.

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:

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 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:

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

you need to change your handleChange to look like this

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. 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

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"

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天全站免登陆