javascript - React Js If Else 使用来自 API 的数据
问题描述
此 data.quotes.USD.percent_change_1h 是从 API 获取数据,我需要它来检查它是否包含“-”(减号)。如果它包含减号,则来自 API 的数据编号颜色为红色,否则为绿色。但不知何故,我的代码不起作用
class Cointable extends React.Component {
constructor(props) {
super(props)
this.state = {
error: null,
isLoaded: false,
data: [],
}
}
componentDidMount() {
this.timer = setInterval(
() =>
fetch(conf[this.props.coin].url)
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
data: result.data,
})
},
error => {
this.setState({
isLoaded: true,
error,
})
}
),
5000
)
}
render(){
const { error, isLoaded, data } = this.state
if (error) {
return <div>Error: {error.message}</div>
} else if (!isLoaded) {
return <div>Loading...</div>
}
return(
//这是主要问题所在
{data.quotes.USD.percent_change_1h.includes('-') === true ? (
<TD style={{ color: 'red' }}>{data.quotes.USD.percent_change_1h}</TD>
) : (
<TD style={{ color: 'green' }}>{data.quotes.USD.percent_change_1h}</TD>
)}
)
}
它让我的桌子都消失了,不会显示任何东西。percent_change_1h 的值类似于“0.7”或“-0.7”
解决方案
你可以这样检查:
data.quotes.USD.percent_change_1h.indexOf('-') > -1