如何检查对象是否包含字符串值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何检查对象是否包含字符串值?相关的知识,希望对你有一定的参考价值。
我知道可以在h标签被填充时读取对象内部的值,但我不能打语句检查。response.image
的值,尽管我的 console.log 显示它确实存在。
我不确定下面的检查值的语义是否正确。我推测我可能需要在return语句之前进行检查。点击 response.result.image
是很好的,但我猜测这是因为我没有像上面的其他2条语句那样检查字符串值。
import React from 'react';
import getResponse from '../Handler/getResponse.jsx';
import Spinner from '../Spinner/Spinner.jsx';
import './Modal.css';
const Modal = ({close, item}) => {
const response = getResponse(item);
console.log(response);
return (
<div>
{response === null &&(<Spinner/>)}
{response &&(
<div className='modal'>
<div className='popup'>
<h1>{response.result.name}</h1>
<h5>{response.result.description}</h5>
{(response.image === "Error") &&(
<p className="text">{response.result.detailedDescription.articleBody}</p>
)}
{response.image && (response.image !== "Error") &&(
<div className="container">
<div className="left">{response.result.detailedDescription.articleBody}</div>
<div className="right"><img className="image" alt="image" src={response.image}/></div>
</div>
)}
{response.result.image &&(
<div className="container">
<div className="left">{response.result.detailedDescription.articleBody}</div>
<div className="right"><img className="image" alt="image" src={response.result.image.contentUrl}/></div>
</div>
)}
<button onClick={ () => { close(false) }}>close me</button>
</div>
</div>
)}
</div>
);
}
export default Modal;
答案
你可以试试这个我想你的响应中忘记了数据键,但我不能确定,因为我没有getResponse()函数?
import React from 'react';
import getResponse from '../Handler/getResponse.jsx';
import Spinner from '../Spinner/Spinner.jsx';
import './Modal.css';
const Modal = ({close, item}) => {
const r = getResponse(item);
const response = r.data;
console.log(response);
// You can check if it is string with this one;
if (typeof response.image === 'String' && response.image !== '') {
console.log('String exists and is not empty')
}
return (
<div>
{response === null &&(<Spinner/>)}
{response &&(
<div className='modal'>
<div className='popup'>
<h1>{response.result.name}</h1>
<h5>{response.result.description}</h5>
{(response.image === "Error") &&(
<p className="text">{response.result.detailedDescription.articleBody}</p>
)}
{response.image && (response.image !== "Error") &&(
<div className="container">
<div className="left">{response.result.detailedDescription.articleBody}</div>
<div className="right"><img className="image" alt="image" src={response.image}/></div>
</div>
)}
{response.result.image &&(
<div className="container">
<div className="left">{response.result.detailedDescription.articleBody}</div>
<div className="right"><img className="image" alt="image" src={response.result.image.contentUrl}/></div>
</div>
)}
<button onClick={ () => { close(false) }}>close me</button>
</div>
</div>
)}
</div>
);
}
export default Modal;
以上是关于如何检查对象是否包含字符串值?的主要内容,如果未能解决你的问题,请参考以下文章