提交按钮无法加载Redux API,FlatList无法渲染接口数据求助
问题排查与修复:Redux数据无法渲染到FlatList
核心错误点
- 属性映射混乱:
mapStateToProps将Redux状态中的state.load.data映射为组件的render属性,但组件内错误地使用load获取数据,完全不匹配;同时mapDispatchToProps将action函数命名为render,与状态映射属性重名,导致命名冲突与逻辑混淆。 - 按钮点击逻辑失效:
handlePress内调用load(data),但load并非映射的dispatch方法,且data未定义,点击按钮无法触发API请求。 - Reducer数据解构错误:Action的payload传递的是
randomfact,但Reducer内错误解构render,导致无法获取新数据,数组追加的是undefined。 - FlatList数据源错误:
FlatList的data属性绑定了不存在的load,而非从Redux映射的真实数据数组。
修正后的代码
1. components/facts.js
import * as React from 'react'; import { View, Text, FlatList, Button } from 'react-native'; import { connect } from 'react-redux'; import { fetchCatFact } from '../redux/actions/index'; const Random = ({ catFacts, fetchCatFact }) => { const handlePress = () => { fetchCatFact(); }; React.useEffect(() => { fetchCatFact(); }, []); return ( <View> <FlatList data={catFacts} renderItem={({ item }) => <Text>{item.result}</Text>} keyExtractor={(item, index) => index.toString()} /> <Button title="Click here to display cat fact" onPress={handlePress} /> </View> ); }; const mapStateToProps = state => ({ catFacts: state.load.data, }); const mapDispatchToProps = (dispatch) => ({ fetchCatFact: () => fetchCatFact(dispatch), }); export default connect(mapStateToProps, mapDispatchToProps)(Random);
2. redux/actions/index.js
import { RENDER_API } from '../actionType/index'; const API = "https://catfact.ninja/fact"; export const fetchCatFact = (dispatch) => { fetch(API) .then((res) => res.json()) .then(json => { const randomfact = { result: json.fact }; dispatch({ type: RENDER_API, payload: { randomfact: randomfact } }); }) .catch((error) => console.log(error)); };
3. reducers/load.js
import { RENDER_API } from '../actionType/index'; const initialState = { data: [] }; export default function(state = initialState, action) { switch(action.type) { case RENDER_API: { const { randomfact } = action.payload; return { ...state, data: [...state.data, randomfact] }; } default: return state; } }
修复逻辑说明
- 统一命名规范:将状态数据映射为
catFacts,action函数重命名为fetchCatFact,彻底避免命名冲突。 - 修正按钮触发逻辑:点击按钮直接调用映射的
fetchCatFact方法,确保API请求正常触发。 - 修复Reducer数据处理:正确从action.payload中解构
randomfact,将新数据追加到状态数组中。 - 规范FlatList配置:使用正确的数据源
catFacts,添加keyExtractor避免React Native渲染警告。
内容的提问来源于stack exchange,提问作者semistupid
相关产品推荐
相关产品推荐

