javascript - 为什么状态不改变?
问题描述
我不明白为什么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")
)
解决方案
您需要更改代码中的一些内容:
您正在尝试访问
prevState
内部setState
,但您没有使用该arrow
功能,因此prevState
isundefined
。您在初始状态数据中声明
fontSize
为 astring
,因此递增不起作用,因为它应该是一个数字。
最后,不要忘记清除.componentWillUnmount
constructor(props) {
super(props);
this.state = { fontSize: 20 };
setInterval(() => {
this.setState(prevState => ({
fontSize: ++prevState.fontSize
}));
}, 1000);
}
请参阅工作示例。
推荐阅读
- c - 在 Raspbian 中分叉进程时进行调试
- c - 计算总和时得到“1.#INF00” 1!/n^1 + 2!/n^2 + ... + n!/n^n
- javascript - 为什么我的 Redux 道具对象返回未定义?
- php - 用户池客户端 {id} 不存在
- java - 我的代码有什么问题。Decryption.txt 不接受 java 文件操作中的任何消息。?
- javascript - 如何在 Chrome 浏览器中使用 javascript 验证有效的 Date 对象
- php - 我想用 php (.htaccess) 重写一个 URL
- python - 使用 MongoDB 更改流时代码不运行
- c++ - 16X32 RGB Led矩阵,矩阵多重定义
- c# - c# linq 包含参数值