首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在JavaScript中使用析构-在一个将被传递给React组件的辅助函数中?

如何在JavaScript中使用析构-在一个将被传递给React组件的辅助函数中?
EN

Stack Overflow用户
提问于 2018-10-09 04:51:41
回答 2查看 40关注 0票数 0

我有这个组件,它接受id作为属性:

代码语言:javascript
复制
<TeamLogo id={team.id} className="center" />

正如你所看到的,它是一个附加到对象的属性。

所以我想到的是:

代码语言:javascript
复制
/* helper function */

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

然后我想像这样使用它:

代码语言:javascript
复制
<TeamLogo id={TeamIdChecker(team.id)} className="center" />

我没有试过,因为我知道我要走了!

提前感谢我的朋友们!

更新这是我的Team组件:

代码语言:javascript
复制
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组件:

代码语言:javascript
复制
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>
  );
}
EN

回答 2

Stack Overflow用户

发布于 2018-10-09 04:55:52

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

代码语言:javascript
复制
if (team.id === undefined)
  return <Redirect to="/" />;
else
  return <TeamLogo id={team.id} className="center" />
票数 3
EN

Stack Overflow用户

发布于 2018-10-09 05:18:04

你可以做一些条件渲染

代码语言:javascript
复制
function TeamIdChecker({ id }) {
  if (id === undefined) return false;
  else return true;
}

然后

代码语言:javascript
复制
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>
    )
}

编辑:

或者更简单,如果这个helper函数只在这里使用

代码语言:javascript
复制
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>
    )
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52709936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档