reactjs - 条件组件内的三元不会在道具更改时重新渲染
问题描述
父级有条件地渲染具有唯一道具的组件。接收这些道具的子渲染函数内部的三元组没有按预期工作。
我已经使用 componentWillRecieveProps 来设置状态,并尝试让三元基于状态。而且,经过研究,我将代码更改为使用函数 getDerivedStateFromProps (因为 componentWillRecieveProps 被认为是不安全的?)代码如下。
此外,我知道组件正确接收了道具,并且状态正在更新为正确的值(由于 console.logs);
class AppearTyping extends React.Component {
constructor(props) {
super(props);
this.state = {
underscore: '',
header: true
}
}
.
.
.
static getDerivedStateFromProps(props, currentState) {
if (currentState.header !== props.header) {
return {
header: props.header,
}
}
return null
}
render() {
let display = this.props.paragraph.join('');
console.log(this.state.header);
return (
<div>
{this.state.header ? <h2 className="about white">{display}
{this.state.underscore}</h2> : <p className="about white">{display}</p>}
</div>
)
}
}
如果组件收到prop: header = true
,我希望{display}
and{this.state.underscore}
被包装在h2
标签中。否则,我希望将组件包装在p
标签中。
解决方案
试试这个,这应该可以,这看起来也很整洁。
render(){
let display = this.props.paragraph.join('');
console.log(this.state.header);
const content = this.state.header ?
<h2 className="about white">
{display}
{this.state.underscore}
</h2> :
<p className="about white">
{display}
</p>;
return <div>
{content}
</div>;
}
尽量保持return
苗条。
推荐阅读
- protractor - 自动化测试的 UI 覆盖率
- c# - 将 .NET Core 项目的测试覆盖率从 Azure DevOps 发布到 SonarCloud
- c# - 如何从一个对象启动两个并行线程?
- django - Dockerized Nginx,域无法正常工作
- swift - Alamofire refreshToken with Retrier:如何获取 refreshToken 请求的状态并重新路由到 LoginView
- ios - 解析问题预期表达式 xcode
- php - 执行触发器时出现 SQL DELIMITER 错误
- java - Java Spring:如何同时运行两个不同的 cronjobs?
- powershell - 试图在 PowerShell 中去除不需要的文本
- youtube - 如何使用 YouTube Live Streaming API 创建 Quick 类型的事件(使用 Google Hangouts On Air)?