The React component can read the data, but when the page is displayed, it always displays the result when musicListDetail.length is 0.

The code for the

component is as follows:

import React from "react";

export default class SimpleListComponent extends React.Component{

    constructor(){
        super();
        this.state = {
            musicList: null,
            currentTitle:"",
            musicListDetail:[]
        }
    }

    componentWillMount(){
        var myFetchOptions = {
            method:"GET"
        }
        var list = null;
        console.log(this.props);
        fetch("http://localhost:3000/musicList?id=" + this.props.columnId, myFetchOptions)
        .then(response=>response.json())
        .then(json => {
            this.setState({musicList:json});

            this.state.musicList[0].details.map((item,index)=>{
                this.state.musicListDetail.push(item);
            });

            this.state.currentTitle = this.state.musicList[0].title;
        })
    }

    render(){
        const {musicListDetail}= this.state;
       
        const musicListContent = musicListDetail.length
        ?  
        this.state.musicListDetail.map((item,index)=>(
            <div key={index} className="m-list-item">
                <a>
                    <img src={item.src}/>
                </a>
                <div>{item.title}</div>
            </div>
        ))
        : 
        <h1 className="m-list-title"></h1>;

        return(
            <div className="m-simple-list-wrapper">
                <h1 className="m-list-title">{this.state.currentTitle}</h1>
                <div className="m-simple-list">
                    {musicListContent}
                </div>
            </div>
        )
    }
}

clipboard.png

when viewing, the data is displayed on the right, but not on the left.

isn"t componentWillMount () executed before render ()? Then the musicListDetail in state should be able to get the value?
later learned that when fetch () gets the data, the page is also in rendering, but it still doesn"t work with componentDidMount ().

Feb.28,2021

well, finally, the part of reading data is written as a method, which can only be called in both componentDidMount () and componentWillMount (). Calling only in one of them will not display

normally.
Menu