reactjs useSelector未更新reduxjs/toolkit中的状态

gkl3eglg  于 2023-03-12  发布在  React
关注(0)|答案(1)|浏览(308)

我尝试使用reduxjs/toolkitstate.user.price状态更新为其他值,但无法正常工作。我知道这与不可变性有关,然后我尝试返回新对象而不更改它们,但无法正常工作。

const initialUserState = {
  isLoggedIn: !!localStorage.getItem("token"),
  carName: "",
  price: "any",
  avaliablity: "any",
  type: "any"
}

const userSlice = createSlice({
  name: "user",
  initialState: initialUserState,
  reducers: {
    handleAuthState: state => {
      state.isLoggedIn = !!localStorage.getItem("token");
    },
    changeCarName: (state, action) => {
      state.carName = action.payload;
    },
    changeAvailablity: (state, action) => {
      state.avaliablity = action.payload;
    },
    changeType: (state, action) => {
      state.type = action.payload;
    },
    changePrice: (state, action) => {
      state.price = action.payload;
    }
  }
});
const store = configureStore({
  reducer: {
    UI: UISlice.reducer,
    user: userSlice.reducer,
    car: carSlice.reducer
  }
});

export default store;
export const userActions = userSlice.actions;
const Filters = () => {
  const type = useSelector(state => state.user.type);
  const price = useSelector(state => state.user.price);
  const carName = useSelector(state => state.user.carName);
  const availablity = useSelector(state => state.user.availablity);

  const sendRequest = async () => {
    console.log("priceInSendRequestFunction = ", price);
  }

  const priceHandler = event => {
    if (event.target.value === "") {
      dispatch(userActions.changePrice("any"))
    } else {
      console.log("event.target.value = ", event.target.value);
      dispatch(userActions.changePrice(event.target.value));
    }
    sendRequest();
  }
  return (
    <Select onChange={priceHandler} placeholder="Select Price">
      <option value="2000">Below 2000</option>
      <option value="4000">2000 - 4000</option>
      <option value="6000">4000 - 6000</option>
      <option value="infinity">Above 6000</option>
      <option value="any">Any</option>
    </Select>
  )
}

sendRequest函数中price的值应获得更新后的值,但它获得了另一个值。

f0brbegy

f0brbegy1#

调用priceHandler时,当前选定的price状态将在回调作用域中关闭。priceHandler将操作调度到存储区并立即调用sendRequest。该组件尚未重新呈现和访问任何更新的Redux状态值。
您可以将该值转发到要将状态更新到的sendRequest

const sendRequest = async (price) => {
  console.log("priceInSendRequestFunction = ", price);
};

const priceHandler = event => {
  const { value } = event.target;
  const newPrice = value || "any";

  console.log({ newPrice });
  dispatch(userActions.changePrice(newPrice));

  sendRequest(newPrice);
};

或者您可以导入store并直接访问当前状态:

import store from '../path/to/store';

...

const sendRequest = async () => {
  const state = store.getState();
  const { price } = state.user;

  console.log("priceInSendRequestFunction = ", price);
};

const priceHandler = event => {
  const { value } = event.target;
  const newPrice = value || "any";

  console.log({ newPrice });
  dispatch(userActions.changePrice(newPrice));

  sendRequest();
};

相关问题