簡體   English   中英

為什么狀態沒有改變?

[英]Why doesn't the state change?

我不明白為什么console.log()有效,但狀態仍然沒有改變?

意味着setState()被調用但未呈現新的...

我嘗試了異步版本setState()但仍無法正常工作。

class Hello extends React.Component {
    constructor(props) {
        super(props);
        this.state = {fontSize: `${20}px`};
        setInterval( 
            () => {
                console.log("ok"); // ok, ok, ok ...
                this.setState(
                    {
                        fontSize: ++prevState.fontSize+"px"
                    }
                )
            },
            1000
        );
    }
    render() {
        let s1 = {
            fontSize: this.state.fontSize
        }
        return <p style={s1}>{this.props.text}</p>;
    }
}

ReactDOM.render(
    <Hello text="sadadadsdad" />,
    document.getElementById("root")
)

您需要在代碼中更改幾件事:

  • 您正在嘗試訪問setState prevState ,但沒有使用arrow功能,因此prevStateundefined

  • 您在初始狀態數據中將fontSize聲明為string ,因此增量將不起作用,因為它應該是數字。

最后,不要忘記在componentWillUnmount 清除該間隔

 constructor(props) { super(props); this.state = { fontSize: 20 }; setInterval(() => { this.setState(prevState => ({ fontSize: ++prevState.fontSize })); }, 1000); } 

請參閱工作示例

暫無
暫無

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

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