首页 > 解决方案 > 存储作为 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 标记中对象的值。有任何想法吗?

标签: jsonreactjsreact-router

解决方案


问题是可以在第一次提交到屏幕之前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..”错误。


推荐阅读