Redux 状态也设置为其他不相关的状态

Redux State is set also to other State that is not Related

编程很奇怪,如果你不这么认为,那么检查这个案例,我使用 createSlices 作为 Redux,我有两个具有自己状态的切片。

第一个是orderSlice:

export const orderSlice = createSlice({
  name: 'order',
  initialState: {
    order: null,
    message: null,
    isLoading: true,
  }
})

而第二个切片是 ordersSlice:

export const orderSlice = createSlice({
  name: 'orders',
  initialState: {
    orders: null,
    message: null,
    isLoading: true,
  }
})

我有这个方法来获取订单和状态设置的完成阶段:

正在获取订单:

export const fetchOrder = createAsyncThunk('', async ({ token, id }) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/view/${id}`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});

正在填写订单状态:

extraReducers: {
    [fetchOrder.fulfilled]: (state, action) => {
      state.order = action.payload.data;
      state.message = 'Succesfully fetched the Order.';
      state.isLoading = false;
    }
  }

这里是获取订单的方法:

export const fetchAllOrders = createAsyncThunk('', async (token) => {
  const requestOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
    },
  };
  try {
    const response = await fetch(`${api}/orders/all`, requestOptions);
    const data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
});

这里更新订单状态:

extraReducers: {
    [fetchAllOrders.fulfilled]: (state, action) => {
      state.orders = action.payload.data;
      state.message = 'Succesfully fetched all Orders.';
      state.isLoading = false;
    }
  }

所以情况是我使用 UseEffect 在订单页面中调用 fetchAllOrders,方法如下:

  import { fetchAllOrders } from '../redux/ordersSlice';
  useEffect(() => dispatch(fetchAllOrders(user.token)), [user]);

这就是我 运行 通过分派获取订单的方法,并且它有效。但问题是,当我 运行 这个函数在 orders 状态旁边填充了相同的数据时, order 状态也填充了相同的数据,这是不可能的,因为我我检查了所有可能输入错误用户的情况,用户打字错误,但我发现 none,但我不知道。

这是商店:

import orderSlice from './redux/orderSlice';
import ordersSlice from './redux/ordersSlice';

const store = configureStore({
  reducer: {
    order: orderSlice,
    orders: ordersSlice
  },
});

你必须给你的 thunk 一个唯一的名字:如果你同时命名 '' 它们将被互换处理。

此外,您应该使用 builder notation for extraReducers。我们将很快弃用您正在使用的对象表示法。