【问题标题】:Cannot read properties of undefined (reading 'map') in react js while using redux使用redux时无法在反应js中读取未定义的属性(读取'map')
【发布时间】:2021-12-24 07:23:18
【问题描述】:

我的后端工作得非常好,即使我与 react js 的 redux 集成也工作得很好,但是一旦我使用 useEffect 它就会给出“无法读取未定义的属性”的错误

下面是我的代码:

const ProductListScreen = ({ match }) => {
  const dispatch = useDispatch()

  const shopDetails = useSelector((state) => state.shopDetails)
  const { loading, error, shop } = shopDetails

  useEffect(() => {
    dispatch(shopDetail(match.params.shopid))
  }, [dispatch, match])

  if (loading) {
    return (
      <div className='loader'>
        <Loader />
      </div>
    )
  }

  return (
    <>
      <Link className='btn btn-dark my-3' to='/'>
        Go Back
      </Link>
      <h3>{shop.name} Products</h3>
      {error ? (
        <Message variant='warning' color='red'>
          {error}
        </Message>
      ) : (
        <Row>
          {shop &&
            shop.products.map((product) => (
              <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                <Product product={product} shopId={shop._id} />
              </Col>
            ))}
        </Row>
      )}
    </>
  )
}

【问题讨论】:

  • console.log(shop.products) //看是不是数组,有没有数据
  • 当我这样做时它显示未定义,但是当注释掉 useEffect 然后控制台记录输出时,它工作得很好:)

标签: javascript reactjs redux e-commerce use-effect


【解决方案1】:
 <Row>
      {shop &&
        shop.products?.map((product) => (
          <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
            <Product product={product} shopId={shop._id} />
          </Col>
        ))}
    </Row>

使用optional chaining operator 跳过未定义产品的地图

可以肯定,购物是真的,所以条件是真的,但是你在映射时仍然没有检查产品的真实性

【讨论】:

  • 非常感谢!这对我有用。
猜你喜欢
  • 1970-01-01
  • 2021-11-19
  • 2022-07-11
  • 2022-07-27
  • 1970-01-01
  • 2021-11-20
  • 2019-04-26
  • 2023-01-11
  • 2022-10-08
相关资源
最近更新 更多