在使用原生android创建桥接后,我正试图访问从NativeModule收到的结果之外的状态。数据显示在console.log中,但无法在外部访问。
NativeModules["GetapplistModule"].getNonSystemApps(res => {
var pairs = [];
for(var key in res){
var obj = JSON.parse(res[key]);
pairs.push(obj);
}
const [AppData] = React.useState(pairs);
});
type AppProps = React.ComponentProps<typeof AppProps>;
export const notificationTweets: Array<AppProps> = {AppData};
我使用useEffect
解决了这个问题
若你们有同样的问题,将你们的函数包装在useEffect中,并在作用域内分配状态,就像这样。
const [AppData, setApps] = React.useState([]);
React.useEffect(() => {
NativeModules["GetapplistModule"].getNonSystemApps(res => {
var pairs = [];
for(var key in res){
var obj = JSON.parse(res[key]);
pairs.push(obj);
}
setApps(pairs);
});
type AppProps = React.ComponentProps<typeof AppProps>;
export const notificationTweets: Array<AppProps> = {AppData};
}, []);
现在,您可以在任何地方访问状态,如
console.log(AppData);
希望这对处理同样问题的人有所帮助。