Loop traversal in react and how to write judgments

Because only expressions can be written in the return of react's render, the for loop and if statement in the js syntax, etc., cannot be used in react
for statements. If we need to loop through the data, we can use the map method. It needs to be wrapped with {}.
For example:
the users here are multiple pieces of data. Use the map method to traverse the users.
The map method needs to set the return value, and the returned structure is the structure that needs to be rendered.
Note: when using the loop traversal, you need to set the key value ( Unique id), set to the outermost structure of the node

export default class List extends Component {
    
    
    render() {
    
    
        const {
    
    users,isFirst,isLoading,err}=this.props
        return (
            <div className="row">
                {
    
    
                    isFirst?<h2>欢迎使用,输入关键字,随后点击搜索</h2>:
                    isLoading?<h2>isLoading......</h2>:
                    err?<h2 style={
    
    {
    
    color:'red'}}>{
    
    err}</h2>:
                    users.map((userObj)=>{
    
    
                        return(
                            <div className="card" key={
    
    userObj.id}>
                                <a rel='noreferrer' href={
    
    userObj.html_url} target="_blank">
                                <img alt='head_ picture' src={
    
    userObj.avatar_url} style={
    
    {
    
    width: '100px'}}/>
                                </a>
                                <p className="card-text">{
    
    userObj.login}</p>
                            </div>
                        )
                    })
                }
                </div>
        )
    }
}

Regarding the if statement, in react we can use the ternary expression instead of the if statement, such as the example in the above code

Guess you like

Origin blog.csdn.net/weixin_48952990/article/details/126448726