【问题标题】:How to automatically change text depending on boolean value in JSON file如何根据 JSON 文件中的布尔值自动更改文本
【发布时间】:2019-12-02 09:40:35
【问题描述】:

我有一个 JSON 文件:

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

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

这是我目前的代码:

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” 并在 availability : true 时保留文本 “Hello” 的任何帮助都会很棒。提前致谢

【问题讨论】:

    标签: javascript json reactjs


    【解决方案1】:

    请给地图添加条件

    <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;
    

    【讨论】:

    • 谢谢,如果这是正确的请投票并标记为答案@RH2019
    【解决方案2】:

    获取后某处,map 的结果如下:

    const processPost = post => post.availability
        ? post 
        : Object.assign({}, post, { text: "Goodbye" });
    
    // ...
    
    fetch("https://api.myjson.com")
        .then(response => response.json())
        .then(posts => posts.map(processPost))
    

    【讨论】:

    • 或者使用es6对象销毁格式:{...post, text: 'Goodbye'}
    • objects... 运算符是 ES2018。在 ES6 中,您只能收集和传播数组等可迭代对象。
    【解决方案3】:

    这很容易通过简单的三元语句来实现。

    return(
        <div>
            <div className="tiles">
            {
                orderedPosts.map(post => (
                    <div key={post.id}>
                     <div className="tile">
                         <p className="greeting">{post.availability ? post.text : 'Goodbye!'}</p>
                     </div> 
                </div>
                ))
            }
            </div>
        </div>
    );
    

    三元文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

    【讨论】:

      【解决方案4】:

      您可以使用三元运算符来显示文本。希望对您有所帮助。

       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">
                           {
                      post.availability:( <p className="greeting">{post.text}</p>)? 
                     (<p className="greeting">Goodbye</p>)
                       }
      
                           </div> 
                      </div>
                      ))
                  }
                  </div>
              </div>
          );
         }
        }
       }
      
       export default GetOnlinePosts;
      

      【讨论】:

        猜你喜欢
        • 2020-03-23
        • 2019-04-17
        • 2020-03-23
        • 1970-01-01
        • 2022-06-25
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 2017-02-22
        相关资源
        最近更新 更多