React Native/Expo中Redux Store无报错但数据不显示求助
React Native/Expo Redux数据不显示的解决方案
1. 核心问题:map函数未返回可渲染元素
在AllRecipes.jsx中,allRecipes.map的回调函数没有返回<Text>元素,导致循环后没有生成任何UI节点,这是数据不显示的直接原因。同时循环元素需要添加key属性避免React警告。
修改后的AllRecipes.jsx代码:
import {View, Text} from 'react-native'; import { useSelector } from 'react-redux'; const AllRecipes = () => { const allRecipes = useSelector(state => state.allRecipes) return ( <View> <Text>All Recipes</Text> {allRecipes.map((r, index) => ( <Text key={index}>{r.name}</Text> ))} </View> ) } export default AllRecipes;
注:如果后续给recipe添加了唯一
id,建议用r.id作为key,比index更稳定。
2. 次要问题:createStore已废弃
你看到的createStore划掉提示是因为它已被Redux官方废弃,推荐使用@reduxjs/toolkit的configureStore创建store,这是当前Redux的标准实践,还默认集成了常用中间件。
操作步骤:
- 安装依赖:
npm install @reduxjs/toolkit react-redux
- 修改
store/index.js:
import { configureStore } from '@reduxjs/toolkit'; import { rootReducer } from './rootReducer'; export const store = configureStore({ reducer: rootReducer, });
3. 确认无误的配置点
你的代码中以下部分已经正确配置,无需修改:
Provider已完整包裹整个应用组件树useSelector的取值路径state.allRecipes与rootReducer中的键名一致
内容的提问来源于stack exchange,提问作者christian_js
相关产品推荐
相关产品推荐

