首页 > 解决方案 > 为什么状态不改变?

问题描述

我不明白为什么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")
)

标签: javascriptreactjs

解决方案


您需要更改代码中的一些内容:

  • 您正在尝试访问prevState内部setState,但您没有使用该arrow功能,因此prevStateis undefined

  • 您在初始状态数据中声明fontSize为 a string,因此递增不起作用,因为它应该是一个数字。

最后,不要忘记清除.componentWillUnmount

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

请参阅工作示例


推荐阅读