[英]Response from Fetch() is undefined
有兩個文件: RegistrationScreen.js和api.js。
在api.js內部,我正在運行fetch()
函數:
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
.then(res => res.json())
/* .then(json => console.warn('JSON: ' + json.userData[0].username))
.catch(e => console.warn('ERROR: ' + e)) */
}
如果對第二個.then()
注釋.then()
可以從響應中看到用戶名 。
我將此功能導入RegistrationScreen.js :
import { fetchAllUsers } from '../../constants/api';
export default class RegistrationScreen extends Component{
static defaultProps = {
fetchAllUsers
}
onCreateButtonPress = async () => {
...
let usernameValidation = await this.checkUsernameUniqueness();
...
}
checkUsernameUniqueness = async () => {
const data = await this.props.fetchAllUsers();
console.warn('user = ' + data)
}
...
}
結果,我進入了控制台用戶= undefined 。 為什么我可以在api.js中看到數據,但在RegistrationScreen.js中卻看不到?
UPDATE_1
如果在RegistrationScreen.js中執行console.warn(this.props.fetchAllUsers)
,我會看到函數代碼,因此該函數可見。
問題是,當您調用fetchAllUsers
您不會從中返回任何內容,這就是為什么獲取undefined
。 沒有return
的函數返回未定義的。
這將返回undefined
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
.then(res => res.json())
/* .then(json => console.warn('JSON: ' + json.userData[0].username))
.catch(e => console.warn('ERROR: ' + e)) */
}
這返回了一個承諾
export const fetchAllUsers = () => {
// added return
return fetch(`http://${localIP}:${port}/api/userData`)
.then(res => res.json())
}
你忘了返回自許fetch
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.