简体   繁体   English

如何使用扩展运算符更改反应状态

[英]How to change react state with spread operator

I need help regarding changing the state of array of objects when fetching data.我需要有关在获取数据时更改对象数组状态的帮助。

This is my use state.这是我的使用状态。

  const [productData, setProductData] = useState<[{label: string, value: string}]>([{
    label: '',
    value: '',
}]);

And this is the function where i make api call and will change my state taking from array of objects the name of the products, so data.name.这是我进行 api 调用的函数,它将改变我的状态,从对象数组中获取产品的名称,所以 data.name。 I am trying to map all the names so that i can show in a dropdown.我正在尝试映射所有名称,以便我可以在下拉列表中显示。

  const getAllProducts = async () => {
    try {
      const { data } = await axios.get(`http://localhost:8300/product/all`);
      data.map((product: any) => setProductData());
    } catch(error) {
      console.log("Error", error);
    }
  };

How would i be able to do this in react typescript.我怎么能在反应打字稿中做到这一点。 Change the label and value field with the mapped values so that i can show in the dropdown.使用映射值更改标签和值字段,以便我可以在下拉列表中显示。

type ProductData = {
  label: string;
  value: string;
};

const [productData, setProductData] = useState<ProductData[]>([
  {
    label: '',
    value: '',
  },
]);
const updateProductData = (newProductData: ProductData[]): void => {
  setProductData((currentState) => {
    const draft = newProductData;

    // mutate your draft however you'd like...

    return [...currentState, ...draft ];
  });
  return;
};
const getAllProducts = async (): ProductData[] => {
  const newProductData = await // ...
  updateProductData(newProductData);
  return;
};

Check the 2nd Note in useState docs检查useState 文档中的第二个注释

You might find useReducer more useful though.不过,您可能会发现useReducer更有用。

You are already making an API call and getting the response here.您已经在进行 API 调用并在此处获得响应。

const getAllProducts = async () => {
  try {
    const { data } = await axios.get(`http://localhost:8300/product/all`);
    data.map((product: any) => setProductData()); <-- prepare your object here
  } catch (error) {
    console.log("Error", error);
  }
};

Once you get the response, prepare the objects that are required for your dropdown.收到响应后,准备下拉列表所需的对象。 Something like below.像下面的东西。

const dropdownValues = data.map((product: any) => ({ id: product.id, label: product.name, value: product.id }));
setProductData(dropdownValues);

Use the ProductData in your dropdown tag.在下拉标签中使用ProductData

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

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