admin管理员组文章数量:1400149
I'm new to React Native and I want to call native modules to get some strings from Android . I write the code like this:
@ReactMethod
public String getToken() {
String token = "";
//then take the token
Log.i("getToken:", token);
return token;
}
Then use in js.
var tokenString = thismodule.getToken();
However ,when i call the method in js. I can see the correct log " I/getToken : palapalapala " in logcat , but js can't get anything.
So , what's the correct code of this?
I'm new to React Native and I want to call native modules to get some strings from Android . I write the code like this:
@ReactMethod
public String getToken() {
String token = "";
//then take the token
Log.i("getToken:", token);
return token;
}
Then use in js.
var tokenString = thismodule.getToken();
However ,when i call the method in js. I can see the correct log " I/getToken : palapalapala " in logcat , but js can't get anything.
So , what's the correct code of this?
Share Improve this question edited Sep 28, 2015 at 5:06 Luo Ruidong asked Sep 28, 2015 at 4:59 Luo RuidongLuo Ruidong 911 silver badge8 bronze badges3 Answers
Reset to default 5Oh,yes . I should know . The municate between js and native is asynchronous . The js method who bridge to the native method , can't return anything now . So , we must sent a callback function to native and get the correct answer in the callback.
That's all.
According to react documentation
To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void. React Native bridge is asynchronous, so the only way to pass a result to JavaScript is by using callbacks or emitting events
@ReactMethod
public void getToken(Callback callback) {
String token = "";
//then take the token
Log.i("getToken:", token);
callback.invoke(token);
}
thismodule.getToken((token) => {
console.log('Result ',token);
}
);
ReactMethod are asynchronuous. So if you want to retrieve data from native to react native you would need to set up the method to return a promise.
See the docs here: https://reactnative.dev/docs/native-modules-android#promises
and in your js file you would need to await that promise or set up a then() function.
Callbacks also work like what Luo wrote.
本文标签: javascriptReact NativeNative modules return nothingStack Overflow
版权声明:本文标题:javascript - React Native : Native modules return nothing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744224400a2596018.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论