我在使用React Native Webview时遇到问题,我想我知道这个问题。在用令牌填充令牌值之前,webview正在运行?如何使Webview在渲染之前等待令牌?
我知道这是原因,如果我运行auth api并获取令牌并将其粘贴到“令牌”所在的位置,则Web视图将正确呈现。
代码:
const getSetData = async() =>{
await AsyncStorage.getItem('token').then((result) => {
token = result;
});
}
return (
<View styles={styles.container}>
<NavigationEvents
onDidFocus = {()=> {
getSetData();
}}
/>
<View style={{alignItems:'center', marginTop: 60}}>
<SLSHeader style={{height: 65, width: '100%'}} navigation={props.navigation} title="RAPID RATES"/>
<View style={{padding:10, top: 20, marginTop:40, marginBottom:10, width:'95%', height:'90%'}}>
<WebView
source={{uri: 'http://myurl.com', headers:{"Authorization":token} }}
style={{ width: '100%', height: '100%'}}
/>
</View>
</View>
</View>
);
答案 0 :(得分:0)
您应该将令牌存储在useState
中。
const [token, setToken] = useState('');
const getSetData = async() =>{
await AsyncStorage.getItem('token').then((result) => {
setToken(result);
});
}
...
{token && <WebView
source={{uri: 'http://myurl.com', headers:{"Authorization":token} }}
style={{ width: '100%', height: '100%'}}
/>}
设置令牌后,组件将重新呈现,并且Webview将加载正确的令牌。
答案 1 :(得分:0)
疯狂的事情是,香港专业教育学院尝试了此操作,令牌控制台却一片空白。
export default function GetHelp (props) {
let [token, setToken] = useState("");
const getSetData = async() =>{
await AsyncStorage.getItem('token').then((result) => {
setToken(token);
//token = result;
});
}
return (
<View styles={styles.container}>
<NavigationEvents
onDidFocus = {()=> {
getSetData();
console.log("Set Token: ", token);
}}
/>
<View style={{alignItems:'center', marginTop: 60}}>
<SLSHeader style={{height: 65, width: '100%'}} navigation={props.navigation} title="RAPID RATES"/>
<View style={{padding:10, top: 20, marginTop:40, marginBottom:10, width:'95%', height:'90%'}}>
<WebView
source={{uri: 'http://myurl.com', headers:{"Authorization":token} }}
style={{ width: '100%', height: '100%'}}
/>
</View>
</View>
</View>
);
}
控制台日志打印为空白?