简体   繁体   English

TypeError: Products.find 不是 (react/typescript) 中的函数

[英]TypeError: Products.find is not a function in( react/typescript)

I use redux thunk我使用redux thunk

why?为什么? find is notFunction find 不是函数

on console log redux given data在控制台日志 redux 上给定数据

help pls I have a strange problem because even data is sent inside the console and I can access the data but can not find in Redax even the initial value of the Hats object求助,我有一个奇怪的问题,因为即使数据是在控制台内部发送的,我可以访问数据,但在 Redax 中甚至找不到 Hats 对象的初始值

my dependency我的依赖

import React, { useEffect } from 'react';
import * as b from 'react-bootstrap';
import { useHistory } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux'
import { productsDetailActions } from '../StateManagement/Actions/productActions';

type Props = {
    match: any;
    params: any;
    pro: any,

}
interface PropsInterface {
    match: Props;
}

const SingleProduct = ({ match }: PropsInterface) => {
    const dispatch = useDispatch()
    console.log(match.params.id)
    useEffect(() => {
        dispatch(productsDetailActions(match.params.id))
    }, [])
    const Products = useSelector((state: any) => (state.productDetail.product))
    console.log(Products)
    const product = Products.find((item: any) => {
     return  item._id === match.params.id
    })
    console.log(product)
    const history = useHistory()


    return (
        <div>
            <b.Row className='my-2 '>
                <b.Col>
                    <b.Button className='btn-danger' onClick={() => history.goBack()}>بازگشت</b.Button>
                </b.Col>
            </b.Row>
            <b.Row>
                <b.Col md={5}>
                    <b.Card className="shadow-sm p-3 mb-5 bg-white">
                        <b.Card.Body className=''>
                            <b.Image src={product && product?.image} fluid />
                            <b.Card.Text className="text-center">{product && product?.description}</b.Card.Text>
                        </b.Card.Body>
                        <b.Card.Body className="text-muted">
                            <h3 style={{ textAlign: 'center' }}>{product && product?.name}</h3>
                        </b.Card.Body>
                    </b.Card>
                </b.Col>
                <b.Col xs={5} md>
                    <b.Card className='shadow-sm p-3 mb-5 bg-white'>
                        <b.Card.Header>
                            <h5 style={{ textAlign: 'center' }}>{product && product?.name}</h5>
                        </b.Card.Header>
                        <b.Card.Body>
                            <b.ListGroup variant='flush'>
                                <b.ListGroup.Item>
                                    {product && product?.description}
                                </b.ListGroup.Item>
                                <b.ListGroup.Item>
                                    {product && product?.name}
                                </b.ListGroup.Item>
                            </b.ListGroup>
                        </b.Card.Body>
                        <b.Card.Footer>
                            <b.Button type='button' className='btn btn-block' >خرید محصول</b.Button>
                        </b.Card.Footer>
                    </b.Card>
                </b.Col>
            </b.Row>
        </div>
    )

}

export default SingleProduct

How can I prevent such problems from occurring?如何防止此类问题的发生? I have a similar one even on the map method我什至在地图方法上也有类似的

and my reducers are the following:我的减速器如下:


interface ActionInterface {
    payload?: any,
    type?:string
}

type state = {
    state: any,
    loading: boolean,
    products?:any
}
const initialState = {
    products: [],
    loading:false,
}
export const productReducers = (state=initialState,action:ActionInterface) => {
    switch (action.type) {
        case 'send_req':
            return { loading: true, products: [] }
        case 'req_success':
            return { loading: false, products: action.payload }
        default:
            return state
    }
}

export const productDetailReducers = (state={product:{}},action:ActionInterface) => {
    switch (action.type) {
        case 'send_req_detail':
            return { loading: true, ...state}
        case 'req_success_detail':
            return { loading: false, product: action.payload }
        default:
            return state
    }
}

and these are the actions :这些是actions

import axios from 'axios'

export const productsActions = () => async (dispatch: any) => {
    
    try {
        dispatch({ type: 'send_req' })
        const response = await axios.get('http://localhost:8001/api/products')
        dispatch({ type: 'req_success', payload: response.data})
    }catch (err) {
        console.log(err)
    }
   
}
export const productsDetailActions = (id:any) => async (dispatch: any) => {
    
    try {
        dispatch({ type: 'send_req_detail' })
        const response = await axios.get(`http://localhost:8001/api/products/${id}`)
        dispatch({ type: 'req_success_detail', payload: response.data })
        console.log(response.data)
    }catch (err) {
        console.log(err)
    }
   
}

There's a chance you are using the wrong keys to grab something from your redux store.您有可能使用错误的密钥从您的 redux 存储中获取某些东西。 You are seeing this error: Product.find is not a function because your Product is likely not an array.您看到此错误: Product.find不是函数,因为您的Product可能不是数组。 I can affirm the above looking at your reducer function for product detail:我可以确认上面看你的减速机功能的产品细节:

export const productDetailReducers = (state={product:{}},action:ActionInterface) => {

Notice that the initial state value here is: product:{} .请注意,这里的初始状态值为: product:{}

hence const Products = useSelector((state: any) => (state.productDetail.product)) will return {} which DOESN'T have a find method.因此const Products = useSelector((state: any) => (state.productDetail.product))将返回没有find方法的{}

Review these lines:查看这些行:

const Products = useSelector((state: any) => (state.productDetail.product))
    console.log(Products)
    const product = Products.find((item: any) => {
     return  item._id === match.params.id
    })

And maybe set product=[] here:也许在这里设置product=[]

export const productDetailReducers = (state={ product:[] }, action: ActionInterface) => {

It'll be helpful if you could share a snippet of your store object.如果您可以分享商店对象的片段,那将会很有帮助。

Tip: you should really ever use any in TS as last resort.提示:你真的应该在 TS 中使用any作为最后的手段。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM