简体   繁体   English

反应:道具未定义

[英]React: props is not defined

I have the following code in a product, js, I'm trying to return a single item on API call using the id param.我在产品 js 中有以下代码,我正在尝试使用 id 参数在 API 调用中返回单个项目。 When I run I get props not defined.当我跑步时,我得到未定义的道具。 I don't know how to solve this我不知道如何解决这个问题

import React, {useEffect }from 'react';

import { detailsProduct } from '../actions/productActions';
  
function Productscreen(props) {

const productDetails = useSelector(state => state.productDetails);

const {product , loading, error } = productDetails;

const dispatch = useDispatch();
useEffect(() => {

  dispatch(detailsProduct(props.match.params.id));

  return () => {
    //
  }
}, [])

在此处输入图像描述

The way you pass the component to your route matters.将组件传递给路由的方式很重要。 To have access to match, you would have needed the render prop to destructure the match.要访问匹配,您将需要渲染道具来解构匹配。

<Route path='/whatever/:id' render={({match}) => <Productscreen match={match} />} />

You can also use the new react router hooks useParams , I prefer them, mostly because of Typescript.你也可以使用新的 react 路由器钩子useParams ,我更喜欢它们,主要是因为 Typescript。

import React, {useEffect } from 'react';
import { detailsProduct } from '../actions/productActions';
import { useParams } from "react-router-dom";

function Productscreen() {
    const productDetails = useSelector(state => state.productDetails);
    const {product , loading, error } = productDetails;

    let { id } = useParams()

    const dispatch = useDispatch();

    useEffect(() => {
         dispatch(detailsProduct(id));`

          return () => {
                //
          }
    }, [])
}

in that case, your route should be:在这种情况下,您的路线应该是:

<Route path="/whateverpath/:id">
  <Productscreen/>
</Route>

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

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