首页 > 解决方案 > 如何检查一个id是否等于用户的id并在react js中有条件地显示按钮?

问题描述

嘿伙计们,我是新手,目前正在尝试根据条件显示 2 个按钮。我需要检查用户是否存在于具有用户 ID 的数组中并显示相应的按钮。

这是我收到的 json 响应。

(2) [{…}, {…}]
0: {id: 8, username: "testuser5"}
1: {id: 4, username: "testuser2"}
length: 2
__proto__: Array(0)

这是我的代码。

const [pending, setPending] = useState([]);

const pendingfun = async function pendingInfo() {
    await axiosInstance.get(url).then((res) => {
        const pending = res.data;
        setPending(pending)
        // console.log(pending)
    })
}

pending.forEach(x => x.id === user.id) ?             
    <Button variant="outlined" color="primary" disableElevation                                         
    >
        Save
    </Button> 
    :   <Button variant="outlined" color="primary" disableElevation>
             Cancel
        </Button>

问题是当我运行它时,屏幕上没有显示任何按钮。有人能帮忙吗?

谢谢

标签: reactjsreact-nativeforeachreact-reduxrxjs

解决方案


forEach不返回任何内容,只对数组进行迭代。您应该使用find来返回正确的按钮:

pending.find(x => (x.id !== user.id)) ?             
    <Button variant="outlined" color="primary" disableElevation                                         
    >
        Save
    </Button> 
    :   <Button variant="outlined" color="primary" disableElevation>
             Cancel
        </Button>
 

推荐阅读