Javascript 为什么';国家不会改变吗?
我不明白为什么Javascript 为什么';国家不会改变吗?,javascript,reactjs,Javascript,Reactjs,我不明白为什么console.log()可以工作,但状态仍然没有改变 表示调用了setState(),但未呈现为新的 我尝试了异步版本setState(),但仍然不起作用 class Hello extends React.Component { constructor(props) { super(props); this.state = {fontSize: `${20}px`}; setInterval( (
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")
)
类Hello扩展了React.Component{
建造师(道具){
超级(道具);
this.state={fontSize:`${20}px`};
设定间隔(
() => {
console.log(“ok”);//好的,好的,好的。。。
这是我的国家(
{
fontSize:++prevState.fontSize++“px”
}
)
},
1000
);
}
render(){
设s1={
fontSize:this.state.fontSize
}
返回{this.props.text}
;
}
}
ReactDOM.render(
,
document.getElementById(“根”)
)
您需要更改代码中的一些内容:
- 您试图访问
内部的prevState
,但您没有使用setState
功能,因此箭头
是prevState
未定义的
- 您在初始状态数据中将
声明为fontSize
,因此递增不起作用,因为它应该是一个数字string
组件中卸载
构造函数(道具){
超级(道具);
this.state={fontSize:20};
设置间隔(()=>{
this.setState(prevState=>({
fontSize:+prevState.fontSize
}));
}, 1000);
}
您需要更改代码中的一些内容:
- 您试图访问
prevState
内部的setState
,但您没有使用箭头
功能,因此prevState
是未定义的
- 您在初始状态数据中将
fontSize
声明为string
,因此递增不起作用,因为它应该是一个数字
最后,不要忘记在组件中卸载
构造函数(道具){
超级(道具);
this.state={fontSize:20};
设置间隔(()=>{
this.setState(prevState=>({
fontSize:+prevState.fontSize
}));
}, 1000);
}