You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native+Redux报错:Cannot read properties of null (reading 'store')

React-Redux 报错:Cannot read properties of null (reading 'store') 解决方法

报错信息

Error:
Cannot read properties of null (reading 'store')
TypeError: Cannot read properties of null (reading 'store')
at eval (react-redux.js:3:6325)
at App (App.js.js:27:33

问题分析及修复

你的代码里有三个关键问题导致了这个报错:

1. useSelector 在 Provider 外层调用

useSelector 必须在被 Provider 包裹的组件内部使用。你在 App 组件顶层直接调用 useSelector,但 Provider 是 App 组件返回的内容,组件渲染时,useSelector 执行时机早于 Provider 生效时机,自然找不到 store,这是报错的核心原因。

解决方法:把使用 useSelector 和 useDispatch 的逻辑抽成子组件,让它被 Provider 包裹。

2. useDispatch 用法错误

useDispatch 是用来获取 dispatch 函数的钩子,不是直接传入 action 对象。你需要先调用 useDispatch() 获取 dispatch 函数,再在点击事件里用它发送 action。

3. Reducer 状态更新不符合不可变性要求

state.counter++ 是原地修改原状态,违反了 Redux 状态不可变的原则,会导致状态更新不生效。应该用 state.counter + 1 生成新数值,返回新的状态对象。

修正后的完整代码

import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { useSelector, useDispatch, Provider } from 'react-redux';
import { createStore } from 'redux';
import Constants from 'expo-constants';

import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';

const initialState = { counter: 0 };
const counterReducer = (state = initialState, action) => {
  const { type } = action;

  if (type === 'INCREMENT') {
    // 修正:用 +1 替代 ++,保证不可变更新
    return { ...state, counter: state.counter + 1 };
  }
  return state;
};
const store = createStore(counterReducer);

// 抽成子组件,放在 Provider 内部
function CounterComponent() {
  const counter = useSelector((state) => state.counter);
  // 修正:先获取 dispatch 函数
  const dispatch = useDispatch();

  return (
    <TouchableOpacity onPress={() => dispatch({ type: 'INCREMENT' })}>
      <Text style={styles.paragraph}>{counter}</Text>
    </TouchableOpacity>
  );
}

export default function App() {
  // 这里不再调用 useSelector,把逻辑移到子组件
  return (
    <Provider store={store}>
      <View style={styles.container}>
        <CounterComponent />
        <Card>
          <AssetExample />
        </Card>
      </View>
    </Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

内容的提问来源于stack exchange,提问作者maddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 21:14:56