簡體   English   中英

Reactjs 在 this.setState() 之后不重新渲染

[英]Reactjs not re-rendering after this.setState()

我正在使用 spotify 的 api 並檢索要設置到 state 的字符串數組,以便通過 JSX 映射到 HTML 中。

將其記錄到控制台表明我確實將正確的數組存儲到 state 中,但 React 從未重新渲染以顯示它們。 如果我在使用自己的值之后再次設置狀態,則該頁面可以正常工作。 也許這是異步的問題?

import React from 'react';
import Button from 'react-bootstrap/esm/Button';
import Spotify from 'spotify-web-api-js';
import Track from './Track';
import Api from '../Api.js'

export default class OtherPage extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            artists:['artists']
        };
        this.getArtists = this.getArtists.bind(this);
    }

    async getArtists(){
        let api = new Api();
        let arr = await api.getTopArtists();
        console.log('arr', arr);
      
        this.setState({artists: arr});
        console.log('new-arr', this.state.artists);

        // this.setState({artists: ['noe', 'tow', 'tre']})

        // console.log('new-new-arr', this.state.artists)
    }

    render(){
        return(
        <div>
            <h1>My Spotify React App!</h1>
            <div className="tracks-container" style={{maxHeight: 500, overflow: 'scroll', margin:50, marginTop:25}}>

                {this.state.artists.map((artist) => 
                    <p>Artist: {artist}</p>
                )}

            <button onClick={() => this.getArtists()}>Get Top Artists</button>
            </div>
        </div>
        );
    };
}

這是 getTopArtists() 的代碼

import React from 'react';
import { Component } from 'react';
import Button from 'react-bootstrap/Button';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Redirect, BrowserRouter as Router, Route, Switch, useHistory } from 'react-router-dom';

class Api extends React.Component{

  async getTopArtists(){
    let arr = [];
    let artists = await fetch("https://api.spotify.com/v1/me/top/artists", {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer '+ localStorage.getItem('access_token')
            }
        }
    ).then((response) => {
        console.log(response.json().then(
            (data) => data.items.forEach(item => arr.push(item.name))
        )
        )});
    console.log(arr);
    return arr;
}
  
 



}

export default Api;

很難確定,但我會嘗試兩個改變:

第一的,

this.setState({artists: [...arr]});

這會強制創建一個新數組,以防萬一api.getTopArtists(); 以某種方式重用相同的數組來獲取結果,這可能導致 React 無法檢測到更改。

第二,

{this.state.artists.map((artist) => 
    <p key={artist}>Artist: {artist}</p>
)}

由於列表上沒有鍵,因此當后備數組發生變化時,很難做出反應來知道列表中發生了什么變化。 可能不是問題,但可能是。

React 有一個名為“ componentDidMount() ”的特殊方法,用於調用外部 API。

隨后從componentDidMount()方法調用外部 API 和 setState 將有助於實現所需的結果。

使用 componentDidMount() 的工作示例:

export default class OtherPage extends React.Component{

    constructor(props){
        super(props)
        this.state = {
            artists:['artists']
        }
    }

    componentDidMount() {
        let api = new Api()
        api.getTopArtists()
           .then((arr) => {
               this.setState({artists: arr}) 
           })
    }

    render() {
        return(
            <div>
                {this.state.artists.map((artist) => 
                    <p>Artist: {artist}</p>
                )}
            </div>
        )
    }
}

更多信息:

https://reactjs.org/docs/faq-ajax.html

暫無
暫無

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

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