【问题标题】:Store a JSON object passed as a prop and how to access its values存储作为 prop 传递的 JSON 对象以及如何访问其值
【发布时间】: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


【解决方案1】:

问题是render 可以被调用(不定次数)第一次提交到屏幕之前,即当组件实际挂载时。

正如您在此处看到的,render 在“渲染阶段”被调用,比“提交阶段”中的componentDidMount 早得多。

您的初始状态为 null,所以这就是您无法访问它的原因。解决这个问题的常见模式是 react conditional rendering

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..”错误.

【讨论】:

    【解决方案2】:

    你可以像这样使用条件渲染:

    <h3>League: {this.state.league? this.state.league.name: "Loading.."} </h3></Row>
    

    或者您可以隐藏整行以避免在屏幕上看到“League:Loading...”。

    当状态更新时,组件会重新渲染并正确显示该字段。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2020-09-23
      • 1970-01-01
      • 2018-12-08
      • 2020-10-07
      • 2019-08-20
      • 2019-03-03
      • 2019-05-18
      • 2020-02-01
      相关资源
      最近更新 更多