React Native,将道具从一个组件导航到另一个组件

React Native, Navigating a prop from one component to another

handleShowMatchFacts = id => {
  //  console.log('match', id)
    return fetch(`http://api.football-api.com/2.0/matches/${id}?Authorization=565ec012251f932ea4000001fa542ae9d994470e73fdb314a8a56d76`)
    .then(res => { 
   //   console.log('match facts', matchFacts)
        this.props.navigator.push({
        title: 'Match',
        component: MatchPage,
        passProps: {matchInfo: res}

     })
       // console.log(res)
  }) 
}
  

我上面有这个功能,我想将 matchInfo 发送到 matchPage。

我在下面收下那个道具

'use strict'

import React from 'react'
import { StyleSheet, View, Component, Text, TabBarIOS } from 'react-native'
import Welcome from './welcome.js'
import More from './more.js'

export default class MatchPage extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount(){

    console.log('mathc facts ' + this.props.matchInfo._bodyInit)
  }



 render(){
  return (
   <View>

      </View>

  )
 }
}

All the info I need is in that object - 'this.props.matchInfo._bodyInit'. My problem is that after '._bodyInt', I'm not sure what to put after that. I've tried .id, .venue, and .events, they all console logged as undefined...

你永远不会在 React 中直接更改 props。您必须始终通过 setState 更改状态并将状态作为道具传递给组件。这允许 React 为你管理状态而不是手动调用。

在您的 api 调用的结果中,设置 组件状态 :

this.setState({
    title: 'Match',
    component: MatchPage,
    matchInfo: res
}

然后根据需要将状态传递给子组件。

render() {
        return(
            <FooComponent title={this.state.title} matchInfo={this.state.matchInfo} />
        );
    }

这些可以在子组件中引用为 props:

class FooComponent extends Component {
    constructor(props) {
        super(props);
    }
    componentWillMount() {
        console.log(this.props.title);
        console.log(this.props.matchInfo);
        // Etc.
    }
}

如果您需要在组件内部引用这些值,请引用 state 而不是 props

this.state.title;
this.state.matchInfo;

记住组件管理它们自己的状态,并根据需要将该状态作为道具传递给子组件。

假设您正在接收 json 对象作为响应,您需要在获取值之前解析响应。

var resp = JSON.parse(matchInfo);
body = resp['_bodyInit'];