简体   繁体   English

我的减速器 function 没有显示我在反应中获取的数据。 我不知道我做错了什么

[英]My reducer function is not displaying the data I'm fetching in react. i dont know what im doing wrong

I'm having trouble diplaying the data im fetching from an API.我无法显示从 API 获取的数据。 when I fetch the data from my app component with componentDidMount it displays all the products.当我使用 componentDidMount 从我的应用程序组件中获取数据时,它会显示所有产品。 but as I try to move the state to context API, I cant seem to get all the products to display.但是当我尝试将 state 移动到上下文 API 时,我似乎无法显示所有产品。 I'm new at this.我是新来的。 i need help seeing what I'm missing.我需要帮助看看我错过了什么。

This is my reducer function这是我的减速机 function

import  { LOAD_ITEMS } from '../types'

export default (state, action) => {
    switch(action.type) {
        case LOAD_ITEMS:
            return {
                ...state,
                products: [...action.payload]
            }

            default: 
            return state
    }
}

Here in my ProductState, I'm trying to fetch data from the API to display it在我的 ProductState 中,我试图从 API 获取数据以显示它

import React, { useReducer } from 'react'
import ProductContext from './ProductContext'
import productReducer from './productReducer'
import {
    LOAD_ITEMS, INCEASE, DECREASE, ADD_ITEM, REMOVE_ITEM, CLEAR, CHECKOUT
} from '../types'

const ProductState = props => {
    const initialState = {
        products: []
    }
   
    const [state, dispatch] = useReducer(productReducer, initialState)

     const loadProducts = async () => {
        
              await fetch('https://fakestoreapi.com/products') 
              .then(res => res.json())
              .then(data => {
                dispatch({
                    type: LOAD_ITEMS,
                    payload: data
                })
              })
             
          }

    return <ProductContext.Provider value={{ 
        products: state.products,
        loadProducts
    }}>
        {props.children}
    </ProductContext.Provider>
}

export default ProductState

This is where I'm importing the productcontext to display the fetched data in my component这是我导入 productcontext 以在我的组件中显示获取的数据的地方

import React, { useContext } from 'react'
import ProductItem from './ProductItem'
import styles from './ProductsGrid.module.scss';
import ProductContext from '../../context/products/ProductContext'

const Products = () => {
    const productContext = useContext(ProductContext)

    const { products } = productContext
        return (
           
            <div className={styles.p__grid}>
                 {products.map(product => (
                        <ProductItem key={product.id} product={product}/>))
                }

            </div>
            <div className={styles.p__footer}>

            </div>
        </div>
        )   
}

export default Products

And this is the root App.js file where I import the ProductState.这是我导入 ProductState 的根 App.js 文件。

import React, { Component, Fragment } from "react";
import {BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from './components/header/Header'
import Store from './components/product/index'
import About from './components/pages/About'
import Cart from './components/cart/Cart'
import ProductState from './context/products/ProductState'


class App extends Component {
  // state={ 
  //   products: []
  // }

  // async componentDidMount() {
  //   try {
  //     const res = await fetch('https://fakestoreapi.com/products') 
  //     const resData  = await res.json();
  //     this.setState({ products: resData })

  //   } catch (err) {
  //     console.error(err);
  //   }
  // }

  render() {
    return (
      <ProductState>
      <Router>
        <Switch>
      <Fragment>
        <Header />
        <div className='container'>
          <Route exact path='/' component={Store} />
          <Route path='/about' component={About}  />
          <Route path='/cart' component={Cart} />
         
        </div>
      </Fragment>
      </Switch>
      </Router>
      </ProductState>
    );
  }
  
}

export default App;

The image below is how it displays when I fetch the data from my app.js下图是我从 app.js 获取数据时的显示方式在此处输入图像描述

The problem seems to be your loadProducts function:问题似乎是您的loadProducts function:

You are using the async keyword incorrectly!您错误地使用了 async 关键字! It should work when you write它应该在你写的时候工作

const loadProducts = async () => {        
          const res = await fetch('https://fakestoreapi.com/products');
          const data = await res.json();
          dispatch({
                type: LOAD_ITEMS,
                payload: data
            });             
         
      }

As you can see, when using async you no longer have to use the usual Promise.then syntax.如您所见,使用 async 时,您不再需要使用通常的Promise.then语法。 You might want to give this MDN page on async await a read.您可能希望在 async await 上阅读此 MDN 页面

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 学校作业,我不知道我做错了什么 - School assignment, i dont know what im doing wrong 我想让它成为一个全局变量,但我不知道我做错了什么替换图像 src 代码 - I want to make this a global variable but I dont know what Im doing wrong replacing image src code 切换ClassList在React中不起作用。 我究竟做错了什么? - ClassList toggling not working in React. What am I doing wrong? “Twilio Quest”挑战,任何帮助将不胜感激,我不知道我做错了什么, - "Twilio Quest" challenge, any help would be appreciated, I dont know what I'm doing wrong, 在满足一定的分数长度后,我试图阻止我的 function 显示元素。 我究竟做错了什么? - I'm trying to stop my function from displaying elements after a certain score length is satisfied. What am I doing wrong? 我不知道为什么我的代码是错误的? 有什么问题吗? - I dont know why my code is wrong ? and what wrong is it? 我无法从属性中提取XML数据,我不知道我做错了什么 - I'm having trouble extracting XML data from attributes and I don't know what I'm doing wrong 我不知道我做错了什么,但是我的带有 js 和 css 的 .html 不会显示必须显示的内容 - I don't know what I'm doing wrong but my .html with js and css won't show what is has to show 我正在尝试在 React 中使用 Threejs。 我的代码中遗漏了什么? - I'm trying to use Threejs in React. What did i miss in my code? 尝试回叫功能时我做错了 - What I'm doing wrong when trying call back function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM