我尝试使用reduxjs/toolkit
将state.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
的值应获得更新后的值,但它获得了另一个值。
1条答案
按热度按时间f0brbegy1#
调用
priceHandler
时,当前选定的price
状态将在回调作用域中关闭。priceHandler
将操作调度到存储区并立即调用sendRequest
。该组件尚未重新呈现和访问任何更新的Redux状态值。您可以将该值转发到要将状态更新到的
sendRequest
:或者您可以导入
store
并直接访问当前状态: