我遇到“无法读取未定义的属性'map'”问题。我打算创建一个“收藏夹”组件,并传递“ AllProducts”收到的相同道具。我将根据“ isSelected”道具在“收藏夹”组件上显示它们。
import React from 'react';
import { Route, Switch } from 'react-router-dom'
import Navigation from './components/Navigation';
import AllProducts from './components/AllProducts/AllProducts';
import Favourites from './components/Favourites'
import './App.css';
function App() {
return (
<div className="App">
<Navigation />
<Switch>
<Route path='/favourites' component={Favourites} />
<Route path='/' ecaxt render={(props) => <AllProducts {...props} />} />
</Switch>
</div>
);
}
export default App;
我的容器组件。
import React, { useState } from 'react';
import AllProducts from '../../components/AllProducts/AllProducts'
const ProductBuilder = (props) => {
const [products, setProducts] = useState([
{ id: 0, title: 'Red Scarf', content: 'A pretty red scarf.', isSelected: false },
{ id: 1, title: 'Blue T-Shirt', content: 'A pretty blue t-shirt.', isSelected: false },
{ id: 2, title: 'Green Trousers', content: 'A pair of lightly green trousers.', isSelected: false },
{ id: 3, title: 'Orange Hat', content: 'Street style! An orange hat.', isSelected: false }
])
const buttonClickHandler = (id) => {
const cloneProducts = [...products];
const cloneElement = { ...cloneProducts[id] };
cloneElement.isSelected = !cloneElement.isSelected;
cloneProducts[id] = cloneElement;
setProducts(cloneProducts)
}
return (
<div>
<AllProducts products={products} buttonClickHandler={buttonClickHandler} />
</div>
);
}
export default ProductBuilder;
我的chlid组件不接收道具。
import React from 'react';
import Product from '../Product'
const AllProducts = (props) => {
let product = (
props.products.map(prd => <Product
key={prd.id}
title={prd.title}
content={prd.content}
id={prd.id}
isSelected={prd.isSelected}
clicked={props.buttonClickHandler}
/>)
)
return (
<div>
{product}
</div>
);
}
export default AllProducts;
我的NavLinks
const Navigation = (props) => {
return (
<Nav>
<Ul>
<li><StyledNavLink to='/' exact > All Products</StyledNavLink> </li>
<li><StyledNavLink to='/favourites' > Favourites </StyledNavLink></li>
</Ul>
</Nav>
);
}
答案 0 :(得分:0)
我认为您要做的就是在使用map之前检查props.products是否未定义。
spans = soup_r.find_all('span',itemprop = 'addressLocality')
# [<span itemprop="addressLocality">Bradford</span>, <span
cities = []
for span in spans:
left_angle=span.find('>'+1)
sec_rangle=spane.find('<',1)
city=span[left_angle:sec_rangle]
print(city)
cities.append(city)
print(cities)
答案 1 :(得分:0)
您所解释的行为是针对您的代码而言的。请注意,使用链接您,(我的意思是您的导航),当您单击指向All Products
的链接时,您仅发送字符串路径名,因此访问产品将为空(因为没有道具products
),请记住,路线的render prop功能可以访问所有相同的路线道具(匹配,位置和历史记录),这意味着通过链接传递类似产品的信息,您要么希望通过传递一个链接就可以做到这一点链接to
的字符串,但是对象是这样的
<Link to ={{pathname: '/', products: "Product array here"}} > All Product </Link>
如果不是这种情况,那么我认为您应该在路由中使用ProductBuilder
。还要查看ProductBuilder的实现,因为您只是将产品数组作为道具直接传递给AllProducts
组件。 React router render method