我在使用React Native构建的应用程序中遇到了一些状态管理问题,所以我决定尝试使用Redux Toolkit。在YouTube上看了几个教程后,我能够实现我需要的功能。不幸的是,当我使用dispatch为变量设置一个新状态时,该状态似乎总是落后一步/状态。例如,根据我的代码;术语";具有初始值"0";弹簧";。有三个按钮(春季、夏季和秋季(。如果我点击";夏季";,警报将显示";弹簧";,这是初始值,如果我随后点击三个按钮中的任何一个;夏季;将显示(这是以前的状态(。显示的状态始终是以前的状态。我的代码逻辑有问题吗?基本上,这三个按钮将用于根据学期/学期更改SQLite查询过滤器。请参阅下面我的代码问题的重新创建。谢谢
TermSlice.js
import { createSlice } from "@reduxjs/toolkit";
export const termSlice = createSlice({
name: "termChanger",
initialState: {
term: 'Spring'
},
reducers: {
setTerm: (state, action) => {
state.term = action.payload;
}
}
});
export const { setTerm } = termSlice.actions;
export default termSlice.reducer;
Store.js
import { configureStore } from "@reduxjs/toolkit";
import termSlice from "./TermSlice";
export default configureStore({
reducer: {
termChanger : termSlice
},
});
主页.js
import React from "react";
import { StyleSheet, View, Button, Text} from "react-native";
import { StatusBar } from "expo-status-bar";
import {useSelector, useDispatch } from "react-redux"
import { setTerm } from "../redux/TermSlice";
export default function Home() {
const dispatch = useDispatch();
const { term } = useSelector((state) => state.termChanger);
return (
<View style={styles.container}>
<Button onPress={() => {
alert(term);
}} title="Term">Term</Button>
<Button onPress={() => {
dispatch(setTerm("Spring"));
alert(term);
}} title="Spring">Spring</Button>
<Button onPress={() => {
dispatch(setTerm("Summer"));
alert(term);
}} title="Summer">Summer</Button>
<Button onPress={() => {
dispatch(setTerm("Fall"));
alert(term);
}} title="Fall">Fall</Button>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
App.js
import React from "react";
import { Provider } from "react-redux"
import store from "./src/redux/Store";
import Home from "./src/screens/Home";
export default function App() {
return (
<Provider store={store}>
<Home />
</Provider>
);
}
dispatch(setTerm("Spring"))
操作和alert(term)
函数都在同一渲染周期中调用,因此alert(term)
使用dispatch
之前的term
值。
您的useSelector
挂钩正在更新。您可以使用useEffect
挂钩来响应term
值的更改,从而使用新值alert
。
或者只是坚持你的";术语";按钮此按钮将获得正确的值,因为它不会改变其显示的term
值。
export default function Home() {
const dispatch = useDispatch();
const term = useSelector((state) => state.termChanger.term);
useEffect(() => {
alert(term);
}, [term]);
return (
<View style={styles.container}>
<Button onPress={() => alert(term)} title="Term">
Term
</Button>
<Button onPress={() => dispatch(setTerm("Spring"))} title="Spring">
Spring
</Button>
<Button onPress={() => dispatch(setTerm("Summer"))} title="Summer">
Summer
</Button>
<Button onPress={() => dispatch(setTerm("Fall"))} title="Fall">
Fall
</Button>
<StatusBar style="auto" />
</View>
);
}