简体   繁体   English

find 方法在我的 React 应用程序中不起作用

[英]find method is not working in my react application

function ProductScreen(props) {
  console.log(props.match.params.id);
  const product = data.products.find((x) => x.id === props.match.params.id);
 console.log(product);
  return (
    <div>
      <h1>{product}</h1>
    </div>
  );
}

In the console of the product, it says undefined.在产品的控制台中,它显示未定义。

I had a similar problem with my React App.我的 React App 也有类似的问题。 When I deployed it to Host server as "... pageData.find((x) => x.id === parseInt(id)); " it returned undefined , but it worked fine in local server.当我将它作为“... pageData.find((x) => x.id === parseInt(id)); ”部署到主机服务器时,它返回了undefined ,但它在本地服务器上运行良好。 I doubt it and changed to == and it worked fine.我怀疑它并更改为==并且它工作正常。 There might be a bug or something.可能有错误或其他东西。

function ProductScreen(props){
   console.log(props.match.params.id);
   const product = data.products.find( x => x._id === props.match.params.id);
   console.log(product);
   return <div>
      <h1>{product.name}</h1>
   </div>
 }

This is working fine you can give product.name or product.id..这工作正常,您可以提供 product.name 或 product.id ..

You need to make sure that you are comparing the same data type between the data.products and props.match.params.id.您需要确保在 data.products 和 props.match.params.id 之间比较相同的数据类型。

The datatype of props.match.params.id is a string. props.match.params.id 的数据类型是一个字符串。 Hence, the data.products.id should be also a string.因此,data.products.id 也应该是一个字符串。

Because props.match.params.id is string and x.id is number that is why it is undefined you should convert props.match.params.id to number因为 props.match.params.id 是字符串而 x.id 是数字,这就是它未定义的原因,您应该将 props.match.params.id 转换为数字

 function ProductScreen(props) {
 const id = Number(props.match.params.id);
 const product = data.products.find((x) => x.id === id);

 return (
  <div>
   <h1>{product}</h1>
  </div>
   );
 }

Use x._id.toString()===match.params.id使用x._id.toString()===match.params.id

const product = data.products.find((x) => x._id == props.match.params.id);

Use == instead of ===使用==而不是===

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

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