【发布时间】:2018-10-08 20:51:41
【问题描述】:
我有这个以 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>
);
}
【问题讨论】:
标签: javascript reactjs ecmascript-6 destructuring