javascript - 在道具集的高阶组件内执行逻辑运算
问题描述
我有一个更高阶的组件,用于执行一些逻辑并将结果作为道具传递给功能组件,以显示数据。
在我的主要组件中,我将道具百分比向下传递给我的 HOC
<Match
inputName={this.state.inputName}
inputSname={this.state.inputSname}
percentage={this.state.percentage}
result={this.state.result}
show={this.state.showResult}
/>
在我的 HOC 里面
我执行一个 switch 语句并将结果作为道具传递给我的功能组件
import React, { Component } from "react";
const MatchWrapper = WrappedComponent => {
return class MatchWrapper extends Component {
state = {
type: ""
};
componentDidMount(){
}
createTypeHandler = () =>{
console.log(this.props.percentage);
console.log(this.props.show)
let type = "";
switch (true) {
case this.props.percentage > 75:
type = "succes";
break;
case this.props.percentage > 50 && 75 >= this.props.percentage:
type = "mediocore";
break;
case this.props.percentage <= 50:
type = "failure123";
break;
}
this.setState({
type: type
});
}
render() {
console.log(this.props.show)
console.log(this.state.type)
{this.props.show &&
this.createTypeHandler
}
return (
<div>
<WrappedComponent type={this.state.type} {...this.props} />
</div>
);
};
}
};
export default MatchWrapper;
现在我有一个关于在哪里渲染我的 createTypeHandler 的问题,我不能把它放在 componentDidMount 中,因为它是在组件安装时渲染的,理想情况下我们希望等待用户传入一些数据。所以我认为最好的选择是制作一个处理程序,要执行,道具展示等于真。
但似乎两者都不起作用?当我现在用户给出输入时,如何渲染函数或设置“类型”的状态?
解决方案
由于结果type
是基于传递的道具,因此您不需要将其保持在状态中。只需在render
方法内部计算即可。
对于这种组件(您不需要也不需要state
任何生命周期方法),您可以使用纯组件
import React from "react";
const MatchWrapper = WrappedComponent => (props) => {
const {show, percentage } = props;
let type = "";
switch (true) {
case percentage > 75:
type = "succes";
break;
case percentage > 50 && 75 >= percentage:
type = "mediocore";
break;
case percentage <= 50:
type = "failure123";
break;
}
return show && <WrappedComponent {...props, type} />
}
export default MatchWrapper;
请注意,原始代码的主要问题是您没有调用createTypeHandler
. 您需要添加()
调用方法。所以this.createTypeHandler()
。但是从方法内部调用一个改变状态的render
方法是一个很大的禁忌。对于这种情况,您需要使用componentDidUpdate
生命周期方法。但是对于这种情况,根本不使用状态会更简单。
推荐阅读
- python - 将 JSON 数据转换为 Pandas DataFrame
- python - 如何在 Django 中连接多个模型
- python-3.x - Ansible Tower 凭据类型未设置环境变量
- visual-studio-code - 在 task.json 中使用 VS Code 扩展变量
- python - 如何在 Python 控制台应用程序的运行之间缓存 ADAL 令牌
- sonarqube - 如何使代码符合:移动此变量以符合 Java 代码约定
- java - 使用 Stream API 将 ArrayList 的嵌套 Map 转换为单行 - Java 函数式编程
- jquery - 如何阻止“搜索”一词出现在可引导搜索中?
- asp.net-core - Recently identityserver 4 auth has started to constantly hit the authorize, and silent renew endpoints
- .net-core - 在 SQL 中存储动态表单数据并作为视图或可能作为存储过程检索