首页 > 解决方案 > 更改我的嵌套状态 React Native 时出现问题

问题描述

我的应用程序中有一个状态,如下所示:

const [companyCategories, setCompanyCategories] = useState({ loading: true, categories: null });

我从 API 获取我的类别并设置我的类别,如下所示:

  const fetchCategories = useCallback(() => {
    fetch(***link***)
      .then(res => {
        if (!res.ok) {
          throw new Error('Failed to fetch.');
        }
        return res.json()
      })
      .then(data => {
        setCompanyCategories({
          loading: false, categories: data.map((el, index) => {
            return {
              id: el.id,
              title: el.title,
              selected: false
            }
          })
        })
      })
      .catch(err => {
        console.log(err);
      });

  }, []);

如果我companyCategories在那之后记录我的:

Object {
  "categories": Array [
    Object {
      "id": 7,
      "selected": false,
      "title": "Casual",
    },
    Object {
      "id": 8,
      "selected": false,
      "title": "Coffe Table",
    },
    Object {
      "id": 10,
      "selected": false,
      "title": "Dining Table",
    },
    Object {
      "id": 11,
      "selected": false,
      "title": "Workstation",
    },
  ],
  "loading": false,
}

这是我的问题:考虑我将此类别显示为应用程序 UI 的按钮,当用户点击每个类别时,它会通过颜色更改,我需要更改selected类别的属性,true默认情况下所有这些都是 false 意味着没有选择. 为此,我编码如下:

  const onRadioBtnClick = (item) => {
    let updatedState = companyCategories.categories.map((el) => {
      if (el.id == item.id) {
        return {
          ...el,
          loading: true,
          categories: {
            ...el.categories,
            selected: !el.selected
          }
        }
      }
      setCompanyCategories(updatedState)
    });
  };

这不起作用,updatedState 正在向我展示undefined。如何操纵嵌套状态的一个属性?

标签: javascriptreactjsreact-native

解决方案


你放setCompanyCategories(updatedState)错了线。

它应该是

const onRadioBtnClick = (item) => {
  let updatedState = companyCategories.categories.map((el) => {
    if (el.id == item.id) {
      return {
        ...el,
        loading: true,
        categories: {
          ...el.categories,
          selected: !el.selected
        }
      }
    }
  });
  setCompanyCategories(updatedState);
};

推荐阅读