React Redux从后端方法获取数据

React Redux从后端方法获取数据,第1张

React Redux从后端方法获取数据

若要执行此最佳做法,请使用以下方法:

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

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

通过创建名称的目录 终极版 或像你的任何名称 src文件夹
,然后创建两个文件

store.js
,并
rootReducer.js
在终极版目录。我们假设从API获取产品。

去做这个:

通过创建名称的新目录 的产品 在终极版目录中,然后通过名称创建四个文件

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.jspackage.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.jsimport { 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.jsimport { 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 在这个文件中,我们选择

products
isFetching
从商店状态。

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.jsimport 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类组件 在此文件中,我们确实连接到商店并使用类组件声明状态

// src/App.jsimport 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);

或具有功能组件(useEffect钩子)的App.js 在此文件中,我们确实连接到具有功能组件的商店和状态

// src/App.jsimport 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);


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5622568.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存