[英]Pass data from Android Native to React Native
我正在構建一個帶有 Android 本機和 React 本機相互通信的集成應用程序。
為了將數據從 Native 發送到 React Native,我嘗試使用初始道具傳遞數據,但它不起作用並顯示未定義。 然后我嘗試使用 DeviceEventEmitter 那種工作,但有一個小問題。
編輯:
這是代碼片段:
class Details extends Component {
constructor(props){
super(props);
this.state={data: '', id: '278'}
}
componentDidMount(){
const eventEmitter = new NativeEventEmitter();
this.subscription = eventEmitter.addListener('customEventName',(e: Event)=>{
this.setState({id: e.key1});
console.warn(this.state.id);
});
const API_key = "APIkey"
console.warn(this.state.id);
const URL = "https://api.themoviedb.org/3/movie/" + this.state.id + "?api_key=" + API_key + "&language=en-USs"
return fetch(URL, {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson,
},
function(){
});
})
.catch((error) =>{
console.error(error);
});
}
componentWillUnmount(){
this.subscription.remove();
}
render() {
return(
/*something*/
);
}
}
id 的值正在成功地從原生組件發送到 React 原生組件。
問題: console.warn()
內addlistener()
是在后示出console.warn()
其是以下聲明API_key
,因此this.state.id
不被更新。
請任何幫助將不勝感激。
您事件寄存器應該是如下提到的那樣,正在注冊的事件,這樣的范圍this
應該是事件處理程序專用的,所以,如果你想訪問父范圍,你需要使用箭頭功能類似下面。
DeviceEventEmitter.addListener('customEventName',(e: Event)=> {
this.id = e.key1
console.warn("inside event emitter", this.id);
});
如果您成功獲得了該事件,那么我認為這只是 React 問題。
看起來您想在成功獲取 ID后獲取,但您正試圖立即在componentDidMount
獲取。
由於 fetch 是一個副作用,您可能希望像這樣使用componentDidUpdate
:
import { NativeEventEmitter } from 'react-native'
constructor(props){
super(props);
this.state={
data: '',
id: ''
}
}
componentDidMount(){
const eventEmitter = new NativeEventEmitter();
this.subscription = eventEmitter.addListener('customEventName',(e: Event)=>{
this.setState({id: e.key1});
console.warn(this.state.id);
});
}
componentDidUpdate() {
const { id } = this.state
if (id) {
const URL = "https://api.themoviedb.org/3/movie/" + this.state.id + "?api_key=" + API_key + "&language=en-USs"
return fetch(URL, {
method: 'GET'
})
// ... etc
}
}
// ...etc
請注意, id
開始時為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.