javascript - 如何在 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>
);
}
解决方案
您不希望<Redirect to="/" />
将其作为属性传递给TeamLogo
,对吗?我只是用
if (team.id === undefined)
return <Redirect to="/" />;
else
return <TeamLogo id={team.id} className="center" />
推荐阅读
- python - 遍历枚举列表 - 如何跳过一个数字?
- algorithm - 持续资源分配/背包问题
- powershell - WSL 上的已删除 Shell 且无法访问 WSL
- java - 从 AbstractTableModel 扩展时如何切换 JTable 中复选框的值
- powershell - 将相同的字符串附加到PowerShell中CSV列中的所有变量
- scala - 编写 spark 脚本来读取文件
- php - 使用 get_the_term 获取所有父母和孩子
- file - WxWidgets,从文件中打印数据
- amazon-web-services - AWS 中的 Lambda 函数是否有 TIMEOUT 环境变量?
- sql - 在Oracle中查询时间段之间