2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
生命周期方法喜歡componentDidMount并render具有標(biāo)準(zhǔn)的角色隔離。通常,前者旨在執(zhí)行一些 API 調(diào)用(如您所擁有的),而后者,render 用于生成標(biāo)記。componentDidMount無(wú)論如何,您應(yīng)該避免嘗試生成標(biāo)記,而不是像它真的可能那樣。
聽(tīng)起來(lái)您要做的就是檢查從 API 返回的項(xiàng)目是否在 localStorage 中可用,然后className根據(jù)其存在有條件地更改該按鈕的 。您可以創(chuàng)建一個(gè)輔助函數(shù)來(lái)幫助您實(shí)現(xiàn)這一目標(biāo)。
checkItem = (item) => {
let className;
if(localStorage.getItem(item["Member_ID"]) != null){
className = "btn btn-success"
} else {
className = "btn btn-warning"
}
return className
}
然后,由于您正在映射項(xiàng)目數(shù)組,因此我們可以根據(jù)您的標(biāo)記調(diào)用此函數(shù)。
render() {
const contents = this.state.data.map(item => (
<tr>
<td>{item.Member_Name}</td>
<td>{item.Member_ID}</td>
<td>{item.Member_DOB}</td>
<td>{item.ProgramType}</td>
<td>
<button id={item.Member_ID} type="button" onClick={(e) => this.downloadUser(item.Member_ID,e)}
className={this.checkItem(item)}>Ready for Download</button>
</td>
</tr>
))
return(
....
{contents}
....
)
}

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
嘗試這個(gè):
componentDidMount{
webApi.get('sai/getofflinemembers?userId=N634806')
.then(event => {
this.setState({
data: event.data
});
})
}
const isExistLocalStorage = value => {
return localStorage.getItem(value) ? true : false;
}
render() {
const { data } = this.state;
return (
data && data.map((item, index) => {
const isExist = isExistLocalStorage(item.Member_ID);
<tr key={index}>
<td>{item.Member_Name}</td>
<td>{item.Member_ID}</td>
<td>{item.Member_DOB}</td>
<td>{item.ProgramType}</td>
<td>
<button
id={item.Member_ID}
type="button"
onClick={(e) => this.downloadUser(item.Member_ID, e)}
className={`btn ${isExist ? "btn-success" : "btn-warning"}`}
> {isExist ? "Ready for Download" : "Not ready"}</button>
</td>
</tr>
})
)
}
添加回答
舉報(bào)