json - 存储作为 prop 传递的 JSON 对象以及如何访问其值
问题描述
所以在 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 标记中对象的值。有任何想法吗?
解决方案
问题是可以在第一次提交到屏幕之前render
调用(不确定次数) ,即当组件实际安装时。
正如您在此处看到的,render
在“渲染阶段”期间调用,比componentDidMount
“提交阶段”要早得多。
不过,您的初始状态为 null,因此这就是您无法访问它的原因。解决这个问题的常见模式是反应条件渲染。
class LeagueInstancePage extends Component {
state = {
league: null
};
componentDidMount(){
const {path} = this.props.match.params
const {league} = this.props.location.state
console.log(path)
console.lot(league)
this.setState({league: this.props.location.state})
}
render() {
const { league: { name } } = this.state;
return name ? (
<Row>
<h3>League: {name} </h3>
</Row>
) : null;
}
}
export default LeagueInstancePage;
注意:在组件状态中复制传递的道具也是一种常见的反模式。在您的情况下,您可以直接访问props.location.state.league.name
,但在用户间接导航到呈现此组件的页面的情况下,仍应使用适当的对象属性访问保护来防御“访问 ... of undefined..”错误。
推荐阅读
- java - 如何在java jar参数中传递&?
- firebase - 如何设置 Firebase 安全读取规则
- xml - Restrictions on a set of values: defining a type usable by many elements (XML Schema)
- python - 对我的 python 函数的异常测试感到困惑
- c++ - C ++中的抽象类类型数组
- android - 颤振:'未来
' 不是类型 'String' 的子类型 - android - 材料日期选择器标题不合适
- apache-kafka - 如何从 kafka 集群中删除 Kafka 代理机器
- amazon-web-services - 为什么我在创建 ec2 实例时收到此权限被拒绝错误?
- url - 将 `/blog${node.fields.slug}` 添加到 createPage 后,Gatsby slug 下一个/上一个问题