简体   繁体   English

如何在 React 的 useEffect 中设置状态?

[英]How to set the state in useEffect in React?

I'm currently working on a project and I need to get the specific data from backend and set the object.我目前正在做一个项目,我需要从后端获取特定数据并设置对象。 However, it is not setting up the object correctly, and it is just setting the last element.但是,它没有正确设置对象,它只是设置最后一个元素。

I'm using ContextAPI for the state management.我正在使用 ContextAPI 进行状态管理。

My API request looks like following which is used to return the specific product from whole products ( axios there is a hook I set up and it gets the uid and function itself is getting the id which is a product id ):我的 API 请求如下所示,用于从整个产品返回特定产品( axios我设置了一个挂钩,它获取uid ,函数本身获取id ,这是一个产品id ):

  const getProductbyId = async (id) => {
    try {
      const response = await axios.get("designer/products", {
        uid: currentAuthData.id,
      });

      const products = response.items;
      const product = products.filter((item) => item.id === parseInt(id));
      return product[0];
    } catch (error) {
      return null;
    }
  }

In my React code, I'm using useEffect to get the specific data and add it to the object.在我的 React 代码中,我使用useEffect获取特定数据并将其添加到对象中。

data here is a Context I'm using and it contains several states.这里的data是我正在使用的上下文,它包含几个状态。 But, I need to use data.setValues here.但是,我需要在这里使用data.setValues

  const data = useData();
  const params = useParams();
  useEffect(() => {
    data.setValues({
      ...data.values,
      step1: 1,
    });
    const getProductbyId = async () => {
      const response = await data.requests.getProductbyId(params.id);
      if (response) {
        response.property_groups.forEach((item, i) => {
          data.setValues({
            ...data.values,
            [`step${i + 2}`]: item.group_property.id,
          });
        });
      }
    };
    getProductbyId();
    data.setStep(2);
  }, []);

The problem appears in data.setValues where it does not add the values (which are ids ) to the object.问题出现在data.setValues中,它没有将值(即ids )添加到对象。

I tried to use useTimeout but it does not solve the problem.我尝试使用useTimeout但它没有解决问题。 To conclude, I want to add the values to data.values object and use it in another React code.总而言之,我想将值添加到data.values对象并在另一个 React 代码中使用它。

Change your method like this,像这样改变你的方法,

const getProductbyId = async () => {
      const response = await data.requests.getProductbyId(params.id);
      if (response) {
        let newValues=response.property_groups.reduce((prev,item,i)=>{
          prev[`step${i + 2}`]= item.group_property.id;
          return prev;
        },{});
        data.setValues({
          ...data.values,
          ...newValues
        });
      }
    };

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

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