简体   繁体   English

为什么状态没有改变?

[英]Why doesn't the state change?

I can't understand why console.log() works, but state still doesn't change? 我不明白为什么console.log()有效,但状态仍然没有改变?

Means setState() is called but not rendered new... 意味着setState()被调用但未呈现新的...

I tried async version setState() but it's still not working. 我尝试了异步版本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")
)

You need to change a couple of things in your code: 您需要在代码中更改几件事:

  • You are trying to access prevState inside setState but you are not using the arrow function thus prevState is undefined . 您正在尝试访问setState prevState ,但没有使用arrow功能,因此prevStateundefined

  • You declared fontSize as a string in your initial state data so incrementing won't work since it should be a number. 您在初始状态数据中将fontSize声明为string ,因此增量将不起作用,因为它应该是数字。

Lastly, don't forget to clear that interval in componentWillUnmount . 最后,不要忘记在componentWillUnmount 清除该间隔

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

See working example . 请参阅工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM