簡體   English   中英

為什么 React 沒有渲染我的 map function?

[英]Why is React not rendering my map function?

我有一個 map function 到一個 state 我確定它不是空的,因為它的狀態已被記錄。

當我加載頁面時,它顯示 div“加載了”,但僅此而已。 控制台也不會注冊他的“運行”日志。

這是針對 CS50W 課程的,所以我使用的是瀏覽器內的 Babel 轉換器。 有人建議我完全改變編譯代碼的方法,但這意味着學習並進行全新的設置,所以我希望這不是它不起作用的原因。

class Posts extends React.Component{
    
    
    constructor(props){     
        super(props)
        this.state = {
            aposts: [],
            isLoaded: false
        }
    } 

    componentDidMount() {
        console.log('running go fetch');
        let currentList = [];
        fetch('/posts')
        .then(response => response.json())
        .then(posts => {
        
            
            
            for (var i = 0; i < posts.length; i++) {
                
                
                currentList.push(posts[i])
                console.log(currentList[i])
                
                
               
                
            }
            
            
        });
        console.log(currentList)

        this.setState({ aposts: currentList, isLoaded: true }, () => {
        console.log(this.state.aposts, 'aposts');
        }); 
        
    } 
     
    
    render(){
        var isLoaded = this.state.isLoaded
        if (isLoaded = true){
        return (
            <div>
                <div>did load</div>
                {this.state.aposts.map(function(apost) {
                console.log("running")    
                return (<li key = {apost.id}> {apost.id} </li>)
                })}
                
            </div>
            );          
        }
        else{
            <div>No load</div>
        }
    }
 componentDidMount() {
        console.log('running go fetch');
        let currentList = [];
        fetch('/posts')
        .then(response => response.json())
        .then(posts => {
        
            for (var i = 0; i < posts.length; i++) {
                currentList.push(posts[i])
                console.log(currentList[i])
            }
            
            console.log(currentList)

            this.setState({ aposts: currentList, isLoaded: true }, () => {
             console.log(this.state.aposts, 'aposts');
            
            });
        });

在制作 api 時調用它需要一些時間,所以 JS 只需在其他進程上運行該工作,您的主進程就會繼續工作。

閱讀有關同步/異步的信息

當您使用.then時,JS 完成 api 調用並從服務器獲取響應,它應該運行內部的任何內容.then

因此,您必須在 .then 中設置 state .then以便在獲取值后為 state 設置值


你說你必須設置並學習設置。 你為什么不使用 [CRA][1] 它會為你設置一切。

暫無
暫無

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

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