[英]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> ) } }
我需要的所有信息都在該對象中-'this.props.matchInfo._bodyInit'。 我的問題是在'._bodyInt'之后,我不確定該放在什么后面。 我已經嘗試過.id,.venue和.events,它們都以未定義的方式登錄到控制台...
您永遠不會在React中直接更改道具。 您必須始終通過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.
}
}
如果您需要在組件本身內部引用這些值,請引用狀態而不是props 。
this.state.title;
this.state.matchInfo;
請記住,組件會管理自己的狀態,並根據需要將該狀態作為道具傳遞給孩子。
假設您正在接收json對象作為response,則需要在獲取值之前解析響應。
var resp = JSON.parse(matchInfo);
body = resp['_bodyInit'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.