【发布时间】:2020-07-11 08:46:54
【问题描述】:
所以在 React 中,我有一个代表足球联赛的 json 对象,其数据如下所示:
{
"league_id": 1,
"name": "World Cup",
"type": "Cup",
"country": "World",
"country_code": null,
"season": 2018,
}
我将它作为道具传递给 React Router Link,如下所示:
<Link className="linktext" to={{
pathname: '/Leagues/' + {nameofLeague},
state: {
league: this.props.league
}
}}>
</Link>
我想打印一些键的值,比如我传递给下面文件的 json 对象的“名称”和“国家”:
class LeagueInstancePage extends Component {
state = {
league: null
};
componentDidMount(){
const {path} = this.props.match.params
***this is the json object and is passed successfully***
const {league} = this.props.location.state
console.log(path)
console.lot(league)
this.setState({league: this.props.location.state})
}
render() {
return (
<h3>League: {this.state.league.name} </h3></Row>
);
}
}
export default LeagueInstancePage;
控制台日志输出工作并且能够像这样打印对象:
问题:
我无法访问文件 render() 中 h3 标记中对象的值。有任何想法吗?
【问题讨论】:
-
我看起来可能在设置状态之前渲染发生了一次,并且您的错误可能在那里发生(但您没有详细说明您如何无法访问该值,具体是什么发生错误)。但是,您应该能够直接从 props 中访问值(除非您想忽略 componentDidMount 之后的 prop 值)。
-
@GarrettMotzner 是对的,当你的组件渲染时 this.state.league 为 null
标签: json reactjs react-router