javascript - 如何在reducer中专门使用redux来获取react-native中的API?
问题描述
如果我们在手机中使用数据来操作或显示,react native state 是常用的并且非常重要,react native 当然有 state 的问题,但是 redux 来解决这个难题,我还是 react 的新手本机,并且只了解如何以“旧”方式获取 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;
朋友.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
});
希望你们给我一些线索,建议,即使答案对我来说也是好的。谢谢你
解决方案
我认为您需要在操作文件中获取数据,而不是在减速器中,然后将您的响应发送到减速器并将其保存在商店中。使用这种方法,您可以随时调用您的操作,这必须适合您。我建议也检查这些链接:
https://redux.js.org/introduction/getting-started
https://stackoverflow.com/questions/43848257/where-to-put-business-logic-in-redux-action-or-store
此链接可能对您有所帮助。
推荐阅读
- c++ - `A a = A()` 有效吗?下面调用了哪些操作符/方法?
- ruby-on-rails - 当我打开上传的文件表单进行编辑时,文件名无法显示
- java - 采用类和同一类的实例的方法,否则编译时错误
- sql - 将相同长度的数组记录相加到新数组中
- ios - 尽管之前已获取过从 firebase 获取的数据,但有时不会将其添加到单元格中
- java - PhantomJs GhostDriver 不允许我点击提交(授予 Box 访问权限)与 chromewebdriver 一起使用
- mongodb - 安装 Mongo db 4 CentOS 6.1 失败
- sql-server - SSIS 无法使用 SQL Server 身份验证连接到 SSMS
- php - 我想做“密码必须至少包含八个字符,包括至少 1 个字母和 1 个数字”。
- ios - Swift Firebase - 通过观察 ref 获得所有评分总和的最有效方法?