简体   繁体   English

更改我的嵌套 state React Native 时出现问题

[英]Problem on changing my nested state React Native

I have a state in my app which is something like following:我的应用程序中有一个 state,如下所示:

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

I fetch my categories from an API and set my categories like below:我从 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);
      });

  }, []);

and if I log my companyCategories after that:如果我在那之后记录我的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,
}

and here's my problem: consider I show this categories as buttons to UI of the app and when user tap on each it changes by the color and I need to alter selected attribute of the category to true which by default all of them are false means that none selected.这是我的问题:考虑我将此类别显示为应用程序 UI 的按钮,当用户点击每个类别时,它的颜色会发生变化,我需要将类别的selected属性更改为true ,默认情况下它们都是 false 意味着未选择。 for this I code like this:为此,我这样编码:

  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)
    });
  };

and this doesn't work, updatedState is showing me undefined .这不起作用, updatedState 向我展示了undefined how can I manipulate one property of my nested state?如何操作嵌套 state 的一个属性?

You placed setCompanyCategories(updatedState) at wrong line.您将setCompanyCategories(updatedState)放在了错误的行。

It should be它应该是

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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM