reactjs - 道具更改时ReactJS子组件不更新
问题描述
我是 ReactJS 的新手,正在做一些练习,这是我的代码。当我单击“显示进度”按钮时,我希望它Progress
会被触发setInterval
并显示最新时间,但它并没有那样工作。它只是显示第一次传递的值并保持不变。
class App extends React.Component{
constructor(props){
super(props);
this.showProgress = this.showProgress.bind(this);
this.state = {
now: new Date(),
content: null
};
this.timerId = null;
}
showProgress(){
let content = <Progress now={ this.state.now } />;
this.setState({ content: content });
}
componentDidMount(){
this.timerId = setInterval(()=>this.setState({now: new Date()}), 500);
}
componentWillUnmount(){
clearInterval(this.timerId);
}
render(){
return (
<div>
<button onClick={ this.showProgress }>Show Progress</button>
{ this.state.content }
</div>
)
}
}
function Progress(props){
return (
<h2>{ props.now.toString() }</h2>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
如果改为嵌入<Progress now={this.state.now}>
intoApp
的render
逻辑,则时间会被刷新setInterval
。
我想知道它有什么问题?
解决方案
您正在将组件存储在状态中。我什至不能 100% 确定这是否有效。
你不能做类似下面的事情吗?
class App extends React.Component{
constructor(props){
super(props);
this.showProgress = this.showProgress.bind(this);
this.state = {
now: new Date(),
content: null,
showProgress: false,
};
this.timerId = null;
}
showProgress(){
this.setState({ showProgress: true });
}
componentDidMount(){
this.timerId = setInterval(()=>this.setState({now: new Date()}), 500);
}
componentWillUnmount(){
clearInterval(this.timerId);
}
render(){
return (
<div>
<button onClick={ this.showProgress }>Show Progress</button>
{this.state.showProgress && <Progress now={ this.state.now } />}
</div>
)
}
}
function Progress(props){
return (
<h2>{ props.now.toString() }</h2>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
推荐阅读
- css - 引导程序和 CSS
- prolog - 如何在序言中获得曾曾祖母
- java - 在 java 澄清中使用 += 和三元运算符
- webpack - 使用“next”运行时,Nextjs 未记录 console.log 或 console.error
- reactjs - React:如何为管理员、用户和公共构建路由
- jenkins - Unable to get BUILD_STATUS global varaible in jenkinsfile
- docusignapi - 如何使用复选框标签数据从模板创建信封?
- javascript - Passing data from parent class to child function -props undefined
- android - Admob AD 单元通过 Firebase 远程配置
- javascript - Chrome 扩展开发:如何使图标 onClick 变灰?