@reduxjs/toolkit状态更新问题:点击按钮无法实现数值递增
React Native + Redux Toolkit 点击按钮数值不递增问题解决
你的代码存在两个核心问题导致数值无法正常递增,同时还有一处可优化的点,具体修复方案如下:
问题1:未正确调用Slice生成的Action
你在counter Slice中定义了increment reducer,但Second组件里直接调用的increment()并未正确引入。Redux Toolkit的createSlice会自动为每个reducer生成对应的Action Creator,需要从counter.actions中解构获取。
问题2:First组件未通过Redux Hooks监听状态变化
First组件直接用store.getState().counter获取状态,这种方式无法让组件感知Redux状态的变化,数值更新时不会触发组件重新渲染,必须使用useSelector Hook订阅状态。
可选优化:使用RTK推荐的configureStore
legacy_createStore是Redux的旧版API,Redux Toolkit提供的configureStore是更推荐的方式,它默认集成了常用中间件,配置更简洁。
修改后的完整代码
import React from "react"; import { View, Text, Button } from "react-native"; import { Provider, useDispatch, useSelector } from "react-redux"; import { configureStore, createSlice, createAction, combineReducers } from "@reduxjs/toolkit"; const incrementBy = createAction('incrementBy') const counter = createSlice({ name: 'counter', initialState: 0, reducers: { increment: (state) => state + 1, multiply: { reducer: (state, action) => state * action.payload, prepare: (value) => ({ payload: value || 2 }) }, }, extraReducers: (builder) => { builder.addCase(incrementBy, (state, action) => { return state + action.payload; }) }, }) // 解构Slice生成的Action Creator const { increment } = counter.actions const reducer = combineReducers({ counter: counter.reducer, }) // 替换旧版store创建方式为RTK推荐的configureStore const store = configureStore({ reducer }) export default () => { return ( <Provider store={store}> <View style={{ flex: 1 }}> <First /> <Second /> </View> </Provider> ); }; const First = () => { // 使用useSelector订阅counter状态 const counter = useSelector(state => state.counter); return ( <View style={{ flex: 1, backgroundColor: "black" }}> <Text style={{ color: "white", fontSize: 40 }}>First : {counter}</Text> </View> ); }; const Second = () => { const counter = useSelector(state => state.counter); const dispatch = useDispatch(); return ( <View style={{ flex: 1 }}> <Text style={{ fontSize: 40 }}>Second : {counter}</Text> {/* 调用正确引入的increment Action */} <Button title="+" onPress={() => dispatch(increment())} /> </View> ); };
内容的提问来源于stack exchange,提问作者Huseyin gökmen
相关产品推荐
相关产品推荐

