【问题标题】:React/Redux can’t access properties of object in an arrayReact/Redux 无法访问数组中对象的属性
【发布时间】:2021-08-23 14:35:30
【问题描述】:

使用 react 和 redux 工具包。

我有一个允许用户创建项目的表单。发布请求必须遵守相关的 mongoose 项目架构。

表单条目与以下状态值相关:

  const [name, setName] = useState('');
  const [imageURL, setImageURL] = useState('');
  const [brand, setBrand] = useState('');
  const [category, setCategory] = useState('');
  const [description, setDescription] = useState('');
  const [barcode, setBarcode] = useState('');
  const [countInStock, setCountInStock] = useState('');
  const [message] = useState(null);
  const [uploading, setUploading] = useState(false);
  const [uploadFile, setupLoadFile] = useState('');

我不希望人们组成自己的类别,所以我有一个单独的类别 mongodb 表,我将其填充到这样的表单中

          <Form.Group controlId='category'>
            <Form.Label>Category</Form.Label>
            <Form.Control
              as='select'
              type='category'
              placeholder='enter Category'
              value={category}
              onChange={(e) => setCategory(e.target.value)}>
              {categories.map((category) => {
                return <option key={category._id}>{category.name}</option>;
              })}
            </Form.Control>
          </Form.Group>

问题是在加载表单时默认显示第一个类别选项,但该选项未设置为类别。因此,如果用户填写表单并且没有触摸类别下拉选项并点击提交,则即使用户看起来像是选择了第一个类别,也会以未定义的类别发送数据。

我尝试通过两种方式解决这个问题:

  1. 让表单触发器 setCategory 加载类别为 默认显示(这不起作用)
  2. 获取第一个类别名称并将其添加到 useState,如下所示:
  const categories = useSelector(getAllCategories);
  let firstCat = categories[0]; //this works
  let firstCatName = firstCat.name; //this fails
  const [category, setCategory] = useState(firstCatName)

此方法失败,因为由于某种原因尝试获取第一个类别的名称会触发错误,即找不到未定义的属性名称,即使该对象存在并且我可以映射表单中的类别数组。

知道我在这里做错了什么吗?

【问题讨论】:

  • 你好阿吉特!我得到一个包含 7 个对象的数组(每个类别一个)
  • 是的,对不起,我这样做并在上面重新发布,我得到了每个类别的对象数组
  • 没问题,这里有一个示例:(8) [{...}, {...}, {...}, {...}, {...}, {...}, {...}, {... }] 0: {_id: "60b48c507d68085a5c99eace", name: "Party", description: "Things to party", __v: 0, createdAt: "2021-05-31T07:12:16.267Z", ...} 1: { _id:“60b48c507d68085a5c99ead1”,名称:“厨房”,描述:“将液体放入这些。或钢笔。”,__v:0,createdAt:“2021-05-31T07:12:16.268Z”,...} ...
  • 成功了,谢谢!我没有意识到你可以在一个屏幕上使用 useEffect 两次!
  • @AjeetShah 请添加您的评论作为答案,以便将其选为正确答案并关闭问题。 谢谢!

标签: reactjs redux react-redux redux-toolkit


【解决方案1】:

来自@Ajeet Shah

useEffect(() => { 
if (categories.length > 0) { 
setCategory(categories[0].name) 
} }, [categories])

我没有意识到你可以在一页中使用两次useEffect,显然你可以!

【讨论】:

  • 您可以使用尽可能多的 useEffect 来满足您的应用需求。你应该查看官方介绍文章:reactjs.org/docs/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2017-02-27
  • 2020-09-09
  • 2017-09-04
  • 2020-05-04
  • 1970-01-01
相关资源
最近更新 更多