我正在构建一个集成Android应用程序与本机和React本机相互通信的应用程序。
为了从Native发送数据到React本机,我试图通过使用初始道具传递数据,但它没有工作并显示未定义。然后我尝试使用哪种工作的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);
});