繁体   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