簡體   English   中英

不確定為什么條件渲染在反應中不起作用

[英]Unsure as to why conditional rendering is not working in react

我正在嘗試根據我從后端收到的包含對象的數組的長度有條件地渲染一些東西。 如果長度為 0,那么我希望它說“無項目”,如果長度 > 0,那么我希望它只在屏幕上顯示項目。 這是我嘗試做的事情:

// Main component handling the filter body
class FilterBody extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // Variables
            projects: null,
            assignment_type: "",
            sdg: [""],
            theme: [""],
            keywords: [""],
            orginization: "",

            jsonLength: 1,
            // Select module features
            isClearable: true,
            isSearchable: true,
        };
  
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    // Handling all 3 input submissions
    handleSubmit(event) {
        event.preventDefault();

        const data = {
            sdg: this.state.sdg, 
            assignment_type: this.state.assignment_type,
            orginization: this.state.orginization,
            keywords: this.state.keywords
        }

        fetch(`/api/projects/filter?sdg=${encodeURIComponent(data.sdg)}&assignment_type=${encodeURIComponent(data.assignment_type)}&orginization=${encodeURIComponent(data.orginization)}&keywords=${encodeURIComponent(data.keywords)}`, {
            method: "GET",
            headers: {
                    'Content-Type': 'application/json;charset=utf-8', 
                },
        })
            .then(response => response.json())
            .then(json => (this.setState({projects: json}), {jsonLength: json.length}))
            .then(jsonLength => console.log(jsonLength)) // DEBUG
        
    }

    async componentDidMount() {
        const response = await fetch('/api/projects')
        const json = await response.json()

        if (response.ok) {
            this.setState({projects: json})
        }
        
    }

    projectDisplay() {
        return (
            <>
                <div className="content">
                    {this.state.projects && this.state.projects.map((project) => (
                        <ProjectDetails key={project._id} project={project}/>
                    ))}
                </div>
            </>
        )
    }


    render() {
      return (
        <>
            <div className="filterHome">
                <div className="filterContainer">
                    

                {/* Lists projects */}
                
                <div className="projects">
                    // THIS IS WHAT I TRIED DOING THE FIRST TIME WHICH DOESN'T WORK
                    {/* {this.state.jsonLength > 0 &&
                        <div className="content">
                            {this.state.projects && this.state.projects.map((project) => (
                                <ProjectDetails key={project._id} project={project}/>
                            ))}
                        </div>
                    }
                    {this.state.jsonLength === 0 &&
                        <div > 
                            No Projects
                        </div>
                    } */}
                    
                    // THIS IS WHAT I TRIED DOING THE SECOND TIME WHICH STILL DOESN'T WORK
                    {this.state.jsonLength > 0 ? this.projectDisplay() : console.log('no projects')}
                    
                    
                </div>
            </div>
        </>
      );
    }
  }
export default FilterBody

這是我第一次嘗試做的事情,一旦有東西來自后端,但這不起作用,並且在jsonLength === 0時什么也不顯示:

{this.state.jsonLength > 0 &&
    <div className="content">
        {this.state.projects && this.state.projects.map((project) => (
            <ProjectDetails key={project._id} project={project}/>
        ))}
    </div>
    }
    {this.state.jsonLength === 0 &&
    <div > 
        No Projects
    </div>
} 

這是我第二次嘗試做的事情,但這也沒有用,當聲明為假時,盡管我輸入了以下內容,但控制台中仍然沒有顯示no projects

{this.state.jsonLength > 0 ? this.projectDisplay() : console.log('no projects')}

有誰知道為什么我的條件渲染不起作用?

setState接受單個 object作為第一個參數,第二個可選參數是回調 function。 它應該是

this.setState({projects: json, jsonLength: json.length})

在我看來,您可以省略jsonLength並改用this.state.projects.length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM