簡體   English   中英

如何在JavaScript中使用解構—在將傳遞給React組件的輔助函數中?

[英]How to use destructing in JavaScript — in a helper function which will be passed to a React component?

我有這個組件,將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>
  );
}

您不希望將<Redirect to="/" />作為屬性傳遞給TeamLogo ,對嗎? 我只是用

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

你可以做一些條件渲染

function TeamIdChecker({ id }) {
  if (id === undefined) return false;
  else return true;
}

然后

render() { // where your rendering your component
    const { id } = team; // wherever that come from, you destruct it here
    return(
        <React.Fragment>
                {TeamIdChecker(id) ? <TeamLogo id={id} className="center" /> : <Redirect to="/" />}
        </React.Fragment>
    )
}

編輯:

甚至更簡單(如果此輔助功能僅在此處使用)

render() { // where your rendering your component
    const { id } = team; // wherever that come from, you destruct it here
    return(
        <React.Fragment>
                {id !== undefined ? <TeamLogo id={id} className="center" /> : <Redirect to="/" />}
        </React.Fragment>
    )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM