React Redux状态不更新且store.getState()无渲染问题求助
Hey there! Let's break down the issues in your code and fix them step by step—you're really close to getting this working!
The Key Problems in Your Code
- Reducer's comma operator mistake: In your reducer, you're using a comma operator in the return statement like
return { ...state, count: 7 }, console.log(...). The comma operator executes all expressions but returns the last one—andconsole.log()returnsundefined. This means your reducer is returningundefinedinstead of the updated state, which breaks Redux's state management entirely. - No auto-re-render on store changes: You're directly calling
store.getState()in your App component, but React has no way to know when the Redux store updates. Even if the state did change, your component won't re-render to show the new value. - Rendering an object directly:
store.getState()returns an object like{count: 5}, so putting it straight into a<Text>component will just show[object Object]instead of the actual number. - Direct store dispatch isn't recommended: Using
store.dispatch()directly bypasses react-redux's component integration tools—we should use the hooks provided by the library instead.
Fixed Code
import React from 'react'; import { Text, Button, View } from 'react-native' import { createStore } from 'redux' import { Provider, useSelector, useDispatch } from 'react-redux' // Define initial state const initialState = { count: 5 } // Fixed reducer const reducer = (state = initialState, action) => { switch (action.type) { case 'NUMBER': console.log("test2", state.count, action.payload); // Return the updated state object first, log separately return { ...state, count: 7 }; default: console.log("test"); return state; } }; // Create store const store = createStore(reducer) // Child component using react-redux hooks const CounterComponent = () => { // Use useSelector to get the count from store (auto-subscribes to changes) const count = useSelector(state => state.count); // Use useDispatch to get the dispatch function const dispatch = useDispatch(); return ( <View> <Text style={{ height: 100, fontSize: 30 }}> {count} </Text> <Button title='Button' onPress={() => { dispatch({ type: 'NUMBER', payload: 6 }) }} /> </View> ) } export default function App() { return ( <Provider store={store}> <CounterComponent /> </Provider > ) }
What Changed & Why
- Fixed the reducer: Moved
console.logbefore the return statement so the reducer always returns a valid state object. - Used
useSelector: This hook lets your component read values from the Redux store and automatically re-renders when those values change. - Used
useDispatch: This is the standard react-redux way to dispatch actions from components, keeping your code aligned with React's component model. - Split into a child component: Separating the counter logic into its own component makes it easier to use the hooks (they only work inside components wrapped by
Provider).
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

