如何使用 React 创建一个大型清单页面? [英] How to create a large checklist page with React?
问题描述
我想创建一个包含 100 个清单项目的页面.将从 Firestore 文档中读取并更新项目.
I want to create a page with 100 checklist items. Items will be read from and updated to a firestore document.
我目前的做法:
// define states which hold checkbox value
const [checkA, setCheckA] = useState(false);
...
...// 100 such states
// writing to firestore
firestore()..
.set({
checkA: checkA
... // 100 key,value pairs
})
// JAX
return(
<checklist
label= 'checkA'
/>
<checklist
label= 'checkB'
/>
... // 100 such components
)
有没有更好、更省力的方法来做到这一点?
Is there a better and less laborious way to do this?
推荐答案
如果你把一个对象存储在 state 中 100 个 item 会不会更简单?
Won't it be easier if you stored a single object in the state for the 100 items?
然后您可以根据逻辑(如果它是一个对象)继续像这样更改状态:
You could then keep changing the state like this depending upon the logic (if it's an object):
setCheckList({...checkList, checkA: false})
当你存储到firestore时,你可以直接使用你状态的对象.
When you store to firestore, you could directly use the object in your state.
编辑
首先,定义一个包含所有清单项的状态变量
First, define a state variable that will hold all the checklist items
const [checkList, setCheckList] = React.useState({checkA: false, checkB: false....100 items})
在您的清单组件中,这是您设置新状态的方式.
In your checklist component, this is how you would set the new state.
<CheckBox label="CheckA" onChange={(value)=>setCheckList({...checkList, checkA: value)} />
<CheckBox label="CheckB" onChange={(value)=>setCheckList({...checkList, checkB: value)} />
你还可以做的是通过 checkList 映射来动态生成 JSX,而不是添加仍然很麻烦的一百个复选框元素,如下所示:
What you can also probebaly do is to generate the JSX for this dynamically by mapping through checkList instead of adding a hundred checkbox elements which is still cumbersome, something like this:
return checkList.map((item, index)=><CheckBox id={index} label={item} onChange={(value)=>{setCheckList({...checkList, [item]: value} />);
最后,存储到 firebase 应该很简单:
Finally, storing to firebase should be as easy as:
firesStore().set(checkList);
这篇关于如何使用 React 创建一个大型清单页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!