首页 > 解决方案 > 在道具集的高阶组件内执行逻辑运算

问题描述

我有一个更高阶的组件,用于执行一些逻辑并将结果作为道具传递给功能组件,以显示数据。

在我的主要组件中,我将道具百分比向下传递给我的 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 中,因为它是在组件安装时渲染的,理想情况下我们希望等待用户传入一些数据。所以我认为最好的选择是制作一个处理程序,要执行,道具展示等于真。

但似乎两者都不起作用?当我现在用户给出输入时,如何渲染函数或设置“类型”的状态?

标签: javascriptreactjs

解决方案


由于结果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生命周期方法。但是对于这种情况,根本不使用状态会更简单。


推荐阅读