我使用 React Native 构建的应用程序遇到了一些状态管理问题,因此我决定尝试使用 Redux-Toolkit。在 YouTube 上观看了几个教程后,我能够实现我需要的功能。不幸的是,当我使用 dispatch 为变量设置新状态时,状态似乎总是落后一步/状态。例如,根据我的代码,变量“term”的初始值为“spring”。共有三个按钮(春季、夏季和秋季)。如果我点击“summer”,警报将显示“spring”,这是初始值,如果我之后点击三个按钮中的任何一个,将显示“summer”(这是之前的状态)。显示的状态始终是之前的状态。我的代码逻辑有问题吗?基本上,这三个按钮将用于根据学期/学期更改 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
},
});
Home.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>
);
}
答案 0 :(得分:0)
dispatch(setTerm("Spring"))
操作和 alert(term)
函数都在同一个渲染周期中调用,因此 alert(term)
使用 term
之前的 dispatch
值.
您的 useSelector
钩子正在更新。您可以通过使用响应 alert
值变化的 useEffect
钩子term
。
或者只是坚持使用“期限”按钮。此按钮将获得正确的值,因为它不会同时更改其显示的 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>
);
}