gpt4 book ai didi

javascript - 如何根据 JSON 文件中的 bool 值自动更改文本

转载 作者:行者123 更新时间:2023-11-29 20:26:55 25 4
gpt4 key购买 nike

我有一个 JSON 文件:

[
{
"id": 1,
"text": "Hello",
"availability": false
},
{
"id": 2,
"text": "Hello",
"availability": true
}
]

我想要实现的是当 availability : false 时文本自动从 hello 变为 goodbye。如果 availability : true 那么我希望它保持显示“Hello”的状态。

到目前为止,这是我的代码:

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
super(props);
this.state = {
error : null,
isLoaded : false,
posts : []
};
}
componentDidMount(){
fetch("https://api.myjson.com")
.then( response => response.json())
.then(
(result) => {
this.setState({
isLoaded : true,
posts : result
});
},
(error) => {
this.setState({
isLoaded: true,
error
})
},
)
}
render() {
const {error, isLoaded, posts} = this.state;
const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
if(error){
return <div>Error in loading</div>
}else if (!isLoaded) {
return <div>Loading ...</div>
}else{
return(
<div>
<div className="tiles">
{
orderedPosts.map(post => (
<div key={post.id}>
<div className="tile">
<p className="greeting">{post.text}</p>
</div>
</div>
))
}
</div>
</div>
);
}
}
}

export default GetOnlinePosts;

availability : false 时将文本从 'Hello' 更改为 'Goodbye' 并保留文本 'Hello' 时的任何帮助availability : true 会很棒。提前致谢

最佳答案

请为 map 添加条件

<p className="greeting">{post.availability ? post.text : 'Goodbye'}</p>

请更改此行

import React, { Component } from 'react';
import './styles.css'

class GetOnlinePosts extends Component {
constructor(props){
super(props);
this.state = {
error : null,
isLoaded : false,
posts : []
};
}
componentDidMount(){
fetch("https://api.myjson.com")
.then( response => response.json())
.then(
(result) => {
this.setState({
isLoaded : true,
posts : result
});
},
(error) => {
this.setState({
isLoaded: true,
error
})
},
)
}
render() {
const {error, isLoaded, posts} = this.state;
const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)]
if(error){
return <div>Error in loading</div>
}else if (!isLoaded) {
return <div>Loading ...</div>
}else{
return(
<div>
<div className="tiles">
{
orderedPosts.map(post => (
<div key={post.id}>
<div className="tile">
<p className="greeting">{post.availability ? post.text : 'Goodbye'}</p> // Change this line
</div>
</div>
))
}
</div>
</div>
);
}
}
}

export default GetOnlinePosts;

关于javascript - 如何根据 JSON 文件中的 bool 值自动更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59136118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com