首页 > 解决方案 > 如何在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
});

希望你们给我一些线索,建议,即使答案对我来说也是好的。谢谢你

标签: javascriptapireact-nativereduxreact-redux

解决方案


我认为您需要在操作文件中获取数据,而不是在减速器中,然后将您的响应发送到减速器并将其保存在商店中。使用这种方法,您可以随时调用您的操作,这必须适合您。我建议也检查这些链接:

https://redux.js.org/introduction/getting-started

https://stackoverflow.com/questions/43848257/where-to-put-business-logic-in-redux-action-or-store

此链接可能对您有所帮助。


推荐阅读