在客户端,我的HomeComponent中有一个模式,可以在其中选择一个元素。然后,我要在同一HomeComponent(在productosEnVenta函数中)中呈现该元素。然后,我在模式中选择的元素是通过ActionCreators中的访存在服务器中进行POST,然后在HomeComponent中显示之前发布的元素。我的问题是,当我从模式中选择元素时,程序会出错,因为它会将我刚刚选择的元素视为未定义,但是当我重新加载浏览器时,该元素显示为正常。我相信这与组件的生命周期有关,但是我不知道是否必须使用componentDidMount或componentDidUpdate来解决此问题。我希望有人能帮助我。
代码如下:
function productosEnVenta(postVenta, preparado, productos, restarCant, deleteCero) {
if (preparado.length > 0){
return(
<div>
{preparado.map((receta) => {
const producto = productos.filter((producto) => producto._id === receta.productoId._id)[0]
return(
<div key={receta._id}>
<Card>
<CardImg src={baseUrl + producto.image} /> //the error is shown here. It says it can't read .image of undefined
<CardTitle>{producto.name}</CardTitle>
</Card>
</div>
);
})}
</div>
);
}
else {
return(
<div><h4>No hay productos preparados</h4></div>
);
}
}
class Home extends Component {
render(){
const ModalElegirReceta = ({putIngrediente, productos, inventario}) => {
const [modal, setModal] = useState(false);
const toggle = () => setModal(!modal);
function restarIngrediente(ingrediente){
for (var elem of ingrediente){
var restar = elem.gramos;
var enInventario = inventario.filter((inven) => inven.ingrediente === elem.ingrediente)[0];
console.log('en inventario: ', enInventario);
var restante = enInventario.disponible - restar;
putIngrediente(enInventario._id, enInventario.ingrediente, enInventario.costo, restante, enInventario.conversiones);
}
}
return(
<div>
<Button onClick={toggle}>Elegir Receta</Button>
<Modal isOpen={modal} toggle={toggle}>
<ModalHeader toggle={toggle}>Elegir Receta</ModalHeader>
<ModalBody>
<Form>
{productos.map((receta) => {
return(
<div className="col-12 col-md-3" key={receta._id}>
<Card onClick={() => {this.props.postPreparado(receta._id, receta.porciones, receta.precio); restarIngrediente(receta.ingredientes)}}>
<CardImg src={baseUrl + receta.image} />
<CardTitle>{receta.name}</CardTitle>
</Card>
</div>
);
})}
</Form>
</ModalBody>
</Modal>
</div>
);
}
return(
<div className="container">
<div className="row row-content">
<div className="col-12">
{productosEnVenta(this.props.postVenta, this.props.preparado.preparado, this.props.productos, this.props.putRestarPreparado, this.props.deleteCero)}
</div>
<div className="col-12 justify-content-center">
<ModalElegirReceta putIngrediente = {this.props.putIngrediente}
productos = {this.props.productos}
inventario = {this.props.inventario}/>
</div>
</div>
</div>
);
}
};
export default Home;
答案 0 :(得分:0)
您可以使用条件渲染来防止错误。
与producto.image
一样,如果您希望producto
在某个时候未定义,则可以编辑函数以返回此值:
return producto && (
<div key={receta._id}>
<Card>
<CardImg src={baseUrl + producto.image} /> //the error is shown here. It says it can't read .image of undefined
<CardTitle>{producto.name}</CardTitle>
</Card>
</div>
);
数据流可能会有更多问题,但这将防止您的应用崩溃。