React Redux从后端方法获取数据

问题描述 投票:0回答:1

我有些困惑,很想得到一个答案,可以帮助我理清思路。假设我有一个后端(nodejs,express等。),我在其中存储用户及其数据,有时我想从后端获取数据,例如他登录后的用户信息或产品列表并保存他们在状态。

到目前为止,以及我所看到的,我在组件加载之前获取数据,并使用响应中的数据调度操作。但是我最近开始对此进行深入研究,并且看到了我较早就知道的react-thunk库,并开始怀疑从后端/ API获取数据的最佳实践是什么?React Hooks对此主题有任何更改吗?知道这一点很重要吗?

我感到有点傻,但找不到与该主题完全相关的文章或视频:)

reactjs redux redux-thunk
1个回答
0
投票

要执行此最佳实践,请使用以下方法:

我使用了一些软件包和模式来进行最佳实践:

  • redux-logger用于浏览器控制台中的日志操作和状态。
  • reselect选择器可以计算派生数据,从而允许Redux存储最小可能的状态,等等。
  • redux-thunk Thunk是推荐的基本中间件Redux副作用逻辑,包括复杂的同步逻辑需要访问存储,以及简单的异步逻辑(例如AJAX请求)等
  • axios用于api(基于Promise的HTTP客户端浏览器和node.js)

通过名称redux或您在src文件夹]中喜欢的任何名称创建目录,然后然后在redux目录中创建两个文件store.jsrootReducer.js。我们假设从API获取产品。

为此:

在redux目录中,通过名称product

创建一个新目录,然后在product.types.js, product.actions.js, product.reducer.js, product.selector.js目录中通过名称redux/product创建四个文件

项目的结构应如下

...
src
  App.js
  redux
    product
      product.types.js
      product.actions.js
      product.reducer.js
    rootReducer.js
    store.js
 Index.js
package.json
...

store.js

在此文件中,我们进行redux配置

// redux/store.js:
import { createStore, applyMiddleware } from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";

import rootReducer from "./root-reducer";

const middlewares = [logger, thunk];

export const store = createStore(rootReducer, applyMiddleware(...middlewares));

rootReducer.js

combineReducers辅助函数将其值为将不同的归约函数合并为一个归约函数传递到createStore

// redux/rootReducer.js
import { combineReducers } from "redux";

import productReducer from "./product/product.reducer";

const rootReducer = combineReducers({
  shop: productReducer,
});

export default rootReducer;

product.types.js

在此文件中,我们定义用于管理动作类型的常量。
export const ShopActionTypes = {
  FETCH_PRODUCTS_START: "FETCH_PRODUCTS_START",
  FETCH_PRODUCTS_SUCCESS: "FETCH_PRODUCTS_SUCCESS",
  FETCH_PRODUCTS_FAILURE: "FETCH_PRODUCTS_FAILURE"
};

product.actions.js

在此文件中,我们创建用于处理动作的动作创建者。
// redux/product/product.actions.js
import { ShopActionTypes } from "./product.types";
import axios from "axios";

export const fetchProductsStart = () => ({
  type: ShopActionTypes.FETCH_PRODUCTS_START
});

export const fetchProductsSuccess = products => ({
  type: ShopActionTypes.FETCH_PRODUCTS_SUCCESS,
  payload: products
});

export const fetchProductsFailure = error => ({
  type: ShopActionTypes.FETCH_PRODUCTS_FAILURE,
  payload: error
});

export const fetchProductsStartAsync = () => {
  return dispatch => {
    dispatch(fetchProductsStart());
    axios
      .get(url)
      .then(response => dispatch(fetchProductsSuccess(response.data.data)))
      .catch(error => dispatch(fetchProductsFailure(error)));
  };
};

product.reducer.js

在此文件中,我们创建productReducer函数来处理动作。
import { ShopActionTypes } from "./product.types";

const INITIAL_STATE = {
  products: [],
  isFetching: false,
  errorMessage: undefined,
};

const productReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case ShopActionTypes.FETCH_PRODUCTS_START:
      return {
        ...state,
        isFetching: true
      };
    case ShopActionTypes.FETCH_PRODUCTS_SUCCESS:
      return {
        ...state,
        products: action.payload,
        isFetching: false
      };
    case ShopActionTypes.FETCH_PRODUCTS_FAILURE:
      return {
        ...state,
        isFetching: false,
        errorMessage: action.payload
      };
    default:
      return state;
  }
};

export default productReducer;

product.selector.js

在此文件中,我们从商店状态中选择productsisFetching
import { createSelector } from "reselect";

const selectShop = state => state.shop;

export const selectProducts = createSelector(
  [selectShop],
  shop => shop.products
);

export const selectIsProductsFetching = createSelector(
  [selectShop],
  shop => shop.isFetching
);

Index.js

在此文件中,将整个应用程序和组件包装为Provider,以便访问子组件以访问商店和州。
// src/Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import { Provider } from "react-redux";
import { store } from "./redux/store";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

App.js类组件

在此文件中,我们确实使用类component
连接到商店并声明了状态
// src/App.js
import React, { Component } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

class App extends Component {
  componentDidMount() {
    const { fetchProductsStartAsync } = this.props;
    fetchProductsStartAsync();
  }

  render() {
    const { products, isProductsFetching } = this.props;
    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);
    return (
      <div className="App">Please see console in browser</div>
    );
  }
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

或具有功能组件的App.js(useEffect钩子)

在此文件中,我们确实连接到具有功能组件的商店和状态
// src/App.js
import React, { Component, useEffect } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  selectIsProductsFetching,
  selectProducts
} from "./redux/product/product.selectors";

import { fetchProductsStartAsync } from "./redux/product/product.actions";

const App = ({ fetchProductsStartAsync, products, isProductsFetching}) => {
  useEffect(() => {
    fetchProductsStartAsync();
  },[]);

    console.log('products', products);
    console.log('isProductsFetching', isProductsFetching);

    return (
      <div className="App">Please see console in browser</div>
    );
}

const mapStateToProps = createStructuredSelector({
  products: selectProducts,
  isProductsFetching: selectIsProductsFetching,
});

const mapDispatchToProps = dispatch => ({
  fetchProductsStartAsync: () => dispatch(fetchProductsStartAsync())
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
© www.soinside.com 2019 - 2024. All rights reserved.