[英]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
.这通常使用扩展运算符和数组函数(例如
map
和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:注意扩展运算符不会在第一级以下操作,我的意思是,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:同样在我的回答中,我使用了空值合并运算符(
??
),如果左操作数是null
或undefined
,这将返回它的右操作数,例如:
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.