【问题标题】:I can't show data in dom after api id matched by conditional在条件匹配的 api id 后,我无法在 dom 中显示数据
【发布时间】:2021-01-23 19:47:32
【问题描述】:

我不能有条件地设置

const [food, setFood] = useContext(UserContext)
  • 当我点击产品时,我会从食物中获得一个 ID
let { img, name, description, price,id } = item;
  • 这是我的 API 项
     food === item.id ?{img, name}: console.log('undifind');
    console.log(name);
  • 问题就在这里
  • 我想在2 id匹配后显示a specific item
import React, { useContext } from 'react'
import { UserContext } from '../../App';

export default function CartInfo({item}) {
    const [food, setFood] = useContext(UserContext)

    let { img, name, description, price,id } = item;

     food === item.id ?{img, name}: console.log('undifind');
    console.log(name);
    return (
        <div className="row">
            <div className="col-md-4"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
        </div>
    )
}

【问题讨论】:

  • 你的意思是每 2 个 id 匹配你想渲染一个 certian 组件?请澄清
  • 当用户点击商品时,id 出现在购物车组件中。如果 id 与 API id 匹配,则用户详细查看该产品。然后该产品显示在 dom
  • 你可以考虑在 API 级别做这个检查而不是查看一个
  • 我可以匹配 id 但我不能显示 dom

标签: reactjs api


【解决方案1】:

你觉得这个解决方案怎么样?

import React, { useContext,useState } from 'react'
import { UserContext } from '../../App';

export default function CartInfo({item}) {
    const [food, setFood] = useContext(UserContext)
    const [showProduct, setShowProduct] = useState(false)
    
    useEffect(() => {
        let { img, name, description, price,id } = item;
        if(food === item.id) {
            setShowProduct(true)
        }
    }, [item]);

    return (
        showProduct ? <div className="row">
            <div className="col-md-4"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
            <div className="col-md-2"></div>
        </div> : null
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多