簡體   English   中英

React Native:通過外部函數更改狀態不會重新渲染

[英]React Native: changing state via external function doesn't rerender

我已經根據需要創建了一個僅在狀態值與以前不相同時更改狀態的函數(即,如果不相同則進行切換)。 但是,它不會重新提供組件。 有人可以讓我知道我在做什么錯嗎? 它確實會改變狀態。

export function toggleState(thi_s, k, new_v)
{
    if(thi_s.state[k]!=new_v)
    {
        thi_s.state[k] = new_v;
        return true;
    }

    return false;
}

[用法]

if(this.state.xyz!=true) this.setState({xyz:true}); //does rerender as expected

toggleState(this, 'xyz', true); //doesn't rerenders 

狀態更改后無需重新發送,我可以在通話后立即使用console.log進行檢查

toggleState您不是在調用setState而是在直接改變狀態,這是您永遠都不應做的,也是未觸發重新渲染的原因:

thi_s.state[k] = new_v;

更改為

thi_s.setState({[k]: new_v});

此外,而不是通過thistoggleState你應該考慮使用箭頭功能或.bind(this) ,而不是讓你可以參考this函數的內部W / O將它作為一個參數。

暫無
暫無

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

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