英文:
Updating part of a setData state
问题
Sure, here's the translated code snippet:
我有一个 Web 应用程序,需要不时获取一些数据。我使用 `zustand` 处理状态,代码如下:
```javascript
import { create } from "zustand";
type State = {
data: any;
setData: (data: any) => void;
};
const returnObjects = {
df: [],
df_other: [],
};
const myData = create<State>((set) => ({
data: returnObjects,
setData: (data) => set((state) => ({ ...state, data: { ...state.data, ...data }})),
}));
export default myData;
然后,我执行了类似以下的数据获取操作:
const { isLoading, isError, isFetching } = useQuery(
"fetch_my_data",
() => fetchData("fetch_my_data", { data1: my_data1, data2: my_data2 }),
{
retry: false,
onSuccess: (newData) => {
setData({ df_other: newData });
}
}
);
基本上,我向后端提供了一些数据,然后它执行某些操作并将数据返回给我。我知道我收到的 newData
是正确的。我的问题出现在通过 setData
替换/更新 data
时。这样做后,df_other
现在具有嵌套名称。所以,不仅 data
具有 df_other
和数据,而且现在 df_other
具有 df_other
和数据。我不太确定如何解决这个“嵌套”问题。
I've translated the code part as you requested. If you have any further questions or need assistance with the code, please feel free to ask.
<details>
<summary>英文:</summary>
I have a web app where I need to fetch some data now and then. I handle the states via `zustand` with the following:
import { create } from "zustand";
type State = {
data: any;
setData: (data: any) => void;,
};
const returnObjects = {
df: [],
df_other: [],
};
const myData = create<State>((set) => ({
data: returnObjects,
setData: (data) => set((state) => ({ ...state, data: { ...state.data, ...data }})),
}));
export default myData ;
I then do a fetch that looks something like:
const {isLoading, isError, isFetching} = useQuery(
["fetch_my_data"],
() => fetchData("fetch_my_data", { data1: my_data1, data2: my_data2}),
{
retry: false,
onSuccess: (newData) => {
setData({ df_other: newData});
}
}
);
So basically I am giving my backend some data, and then it does something and returns it to me. I know that what I get back (`newData`) is correct. My problems arise when replacing/updating the `data` via `setData`. Doing this, `df_other` now have a nested name. So instead of just `data` having `df_other` and then the data, it now has `df_other` which then have `df_other` and then the data. And I'm not really sure how I remove this "nesting" problem.
</details>
# 答案1
**得分**: 1
我希望这段代码对你有帮助:
```javascript
setData: (data) =>
set((state) => ({ ...state, data: { ...state.data, ...data } }));
然后:
setData({ df_other: newData.df_other });
英文:
I hope this code helps you:
setData: (data) =>
set((state) => ({ ...state, data: { ...state.data, ...data } }));
And then:
setData({ df_other: newData.df_other });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论