首页 > 解决方案 > 如何在 JavaScript 中使用析构函数——在将传递给 React 组件的辅助函数中?

问题描述

我有这个以 id 作为属性的组件:

<TeamLogo id={team.id} className="center" />

如您所见,它是附加到对象的属性。

所以我想出的是:

/* helper function */

  function TeamIdChecker({ id }) {
      if (id === undefined) return <Redirect to="/" />;
      else return team.id;
  }

然后我想像这样使用它:

<TeamLogo id={TeamIdChecker(team.id)} className="center" />

我没有尝试,因为我知道我已经离开了!

提前感谢我的朋友们!

更新 这是我的Team组件:

import { Component } from "react";
import PropTypes from "prop-types";
import { getTeam } from "../api";

export default class Team extends Component {
  static propTypes = {
    id      : PropTypes.string.isRequired,
    children: PropTypes.func.isRequired
  };
  state = {
    team: null
  };
  componentDidMount() {
    this.fetchTeam(this.props.id);
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.id !== nextProps.id) {
      this.fetchTeam(nextProps.id);
    }
  }
  fetchTeam = id => {
    this.setState(() => ({ team: null }));
    getTeam(id).then(team => this.setState(() => ({ team })));
  };
  render() {
    return this.props.children(this.state.team);
  }
}

这是我的TeamLogo组件:

import React from "react";
import PropTypes from "prop-types";

const logos = {
  // logo key and values
};

TeamLogo.propTypes = {
  id: PropTypes.string.isRequired
};

TeamLogo.defaultProps = {
  width: "200px"
};

export default function TeamLogo(props) {
  return (
    <svg {...props} x="0px" y="0px" viewBox="0 0 125.397 125.397">
      {logos[props.id]}
    </svg>
  );
}

标签: javascriptreactjsecmascript-6destructuring

解决方案


您不希望<Redirect to="/" />将其作为属性传递给TeamLogo,对吗?我只是用

if (team.id === undefined)
  return <Redirect to="/" />;
else
  return <TeamLogo id={team.id} className="center" />

推荐阅读