如何在reducer中专门使用redux来获取react-native中的API?
Posted
技术标签:
【中文标题】如何在reducer中专门使用redux来获取react-native中的API?【英文标题】:How to fetch API in react-native specially using redux in the reducer? 【发布时间】:2019-09-23 23:19:44 【问题描述】:如果我们在手机中使用数据来操作或显示,React Native 状态是常用的并且非常重要,React Native 的状态当然有问题,但是 Redux 来解决这个难题,我还是新手反应原生的家伙,只是了解如何以“旧”方式获取 API,而不是使用 redux,但是如何?在减速器中,我试图在我的组件中调用我的函数和回调,但没有奏效,代码如下:
peopleReducer.js:
import ADD_FRIENDS from "../types";
import INIT_PEOPLE from "../states";
const peopleReducers = (state = INIT_PEOPLE, action) =>
switch (action.type)
// // save image
case ADD_FRIENDS:
// find how to fetch API in react native redux
makeRemoteRequest = () =>
const page, seed = state;
const url = `https://randomuser.me/api/?seed=$seed&page=$page&results=20`;
setState( loading: true );
fetch(url)
.then(res => res.json())
.then(res =>
setState(
data: page === 1 ? res.results : [...state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
);
console.warn(res.results);
)
.catch(error =>
setState( error, loading: false );
);
;
default:
return state;
;
export default peopleReducers;
friends.js
import React from "react";
import View, Text, FlatList, ActivityIndicator from "react-native";
import ListItem, SearchBar from "react-native-elements";
// connect to redux
import connect from "react-redux";
import bindActionCreators from "redux";
// import actions
import addFriends from "../config/redux/actions/peopleActions";
class friends extends React.Component
componentDidMount()
this.props.addFriends();
// this.makeRemoteRequest();
render()
// console.warn(this.props.peopleListDashboard.data)
return (
<View>
<FlatList
data=this.props.peopleListDashboard.data
renderItem=( item ) => (
<ListItem leftAvatar= uri: item.picture.thumbnail />
)
keyExtractor=item => item.email
/>
</View>
);
// make accesible publicDashboard properties from reducer
const mapStateToProps = state =>
const peopleListDashboard = state;
return peopleListDashboard ;
;
const mapDispatchToProps = dispatch =>
bindActionCreators(
addFriends
,
dispatch
);
export default connect(
mapStateToProps,
mapDispatchToProps
)(friends);
关于触发器,是的,我正在使用动作 peopleAction.js
import ADD_FRIENDS from "../types";
export const addFriends = friendsIndex => (
type: ADD_FRIENDS,
payload: friendsIndex
);
希望你们能给我一些线索、建议,甚至答案对我来说都是好的。谢谢你
【问题讨论】:
【参考方案1】:我认为您需要在操作文件中获取数据,而不是在减速器中,然后将您的响应发送到减速器并将其保存在商店中。使用这种方法,您可以随时调用您的操作,这必须适合您。我建议也检查这些链接:
https://redux.js.org/introduction/getting-started
https://***.com/questions/43848257/where-to-put-business-logic-in-redux-action-or-store
此链接可能对您有所帮助。
【讨论】:
以上是关于如何在reducer中专门使用redux来获取react-native中的API?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Redux Reducer 中使用 GraphQL Mutations
为啥我们在 Flux/Redux 架构中解耦 action 和 reducer?
如何重用 Redux Toolkit createSlice 函数中的 reducer 逻辑?