首页 > 解决方案 > 如何从 JSON 对象访问数据?

问题描述

在我的 react-native-webview 的 onMessage 道具中,我正在接收本机事件,如下所示

 {"nativeEvent": {"canGoBack": true, "canGoForward": false, "data": "{\"url\":\"some_url"}", "loading": false, "target": 313, "title": "Doctors Platform", "url": "some_url"}}

我想访问数据对象中的 url 值,知道怎么做吗?

我的代码:

 <WebView
    source={{
      uri: uri,
    }}
    renderLoading={renderLoadingView}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    startInLoadingState={true}
    // onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} //ios
    onNavigationStateChange={onShouldStartLoadWithRequest} //android
    ref={webviewRef}
    injectedJavaScript={jsCode}
    onMessage={(event) => {
      let post = JSON.stringify(event.nativeEvent.data);
      console.log(event)
      console.log('post',post.message)
    }}
  />

任何建议都会很棒,请让我知道为了更好地理解需要任何东西。

标签: javascriptreactjsreact-nativereact-native-androidreact-native-ios

解决方案


如果您JSON.parse在 data 属性上使用,那么使用.url它将返回您想要的结果。

const myevent =  {"nativeEvent": {"canGoBack": true, "canGoForward": false, "data": "{\"url\":\"some_url\"}", "loading": false, "target": 313, "title": "Doctors Platform", "url": "some_url"}};

console.log(JSON.parse(myevent.nativeEvent.data).url);


推荐阅读