簡體   English   中英

為什么在突變后反應 Js 中不呈現新的狀態值

[英]Why new value of state is not rendered in react Js after mutation

我正在類組件中處理 React Js 我聲明了一些狀態,然后從 API 獲取數據並將該狀態更改為新值,但 React 並未呈現該狀態的新值。 但是如果我 console.log() 那個狀態它給了我控制台上的新值。

如果我訪問另一個頁面然后返回到這個頁面,那么它正在呈現狀態 (3) 的新值。

我的代碼

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            unread:0,
        }
        this.getUnread()   
    } 
getUnread = async() => {
        let data = await Chatapi.get(`count/${this.props.auth.user.id}/`).then(({data})=>data);
        this.setState({unread:data.count});
        console.log(this.state.unread)
    }
render() {
        const { auth } = this.props;
    return(
    <div>
    {this.state.unread}
    </div>
)}

這是在控制台上打印 3 但在屏幕上呈現 0。 如何獲得更新的 state(3) 以在屏幕上呈現。

async/awaitPromise.then()是處理異步操作的兩種不同方法。 所以你應該決定並使用它們中的一個,而不是同時使用它們。 您可以使用以下方法之一:

getUnread = async() => {
  const data = await Chatapi.get(`count/${this.props.auth.user.id}/`)
  this.setState({ unread:data.count });
  console.log(this.state.unread)
}
getUnread = async() => {
  Chatapi.get(`count/${this.props.auth.user.id}/`).then(data => this.setState({ unread:data.count }) )
  console.log(this.state.unread)
}

暫無
暫無

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

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