【问题标题】:Using Rematch Store in React Native在 React Native 中使用 Rematch Store
【发布时间】:2021-10-01 02:13:12
【问题描述】:

我正在使用 expo 在 React Native 中构建一个屏幕。我是 React Native 和 Rematch 框架的新手,我想在加载时从这个端点渲染篮球运动员的名字和姓氏:https://www.balldontlie.io/api/v1/players

这是我的models.js

import axios from "axios";

export const players = {
  state: {
    players: [],
  },
  reducers: {
    SET_PLAYERS: (state, payload) => {
      return {
        ...state,
        players: payload,
      };
    },
  },
  effects: (dispatch) => ({
    async getPlayers() {
      let response = await axios.get(
        "https://www.balldontlie.io/api/v1/players"
      );
      let { data } = await response.json();
      console.log(data);
      dispatch.players.SET_PLAYERS(data);
    },
  }),
};

store.js

import { init } from "@rematch/core";
import * as models from "./models";
const store = init({ models });
export default store;

最后,我的主屏幕:

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Provider } from "react-redux";
import store from "./state_management/store";

export default function App() {
  return (
    <View style={styles.container}>
      <Players />
      <StatusBar style="auto" />
    </View>
  );
}

const Players = () => {
  return (
    <Provider store={store}>
      // PLAYER LIST HERE!!
    </Provider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

我在网上和这里看到的大多数示例都与 onPress 操作有关,例如递增、递减等。这涉及管理来自 API 调用的数据,所以我不知道该怎么做。

【问题讨论】:

    标签: javascript reactjs react-native react-redux expo


    【解决方案1】:

    在您使用功能组件时在主屏幕中尝试使用 useDispatch 和 useSelector 来调度和获取列表并将其映射到您的屏幕

     import { useDispatch, useSelector } from "react-redux";
    
     const dispatch = useDispatch();
    
      const responseList = useSelector(state => {
        return state.apiReducer.data
      })
    

    在 useEffect 向模型发送动作

    从我理解的问题来看,需要从模型中获取存储的列表并渲染玩家名称,请在 link 中找到相同的代码

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多