【发布时间】:2019-04-29 16:26:03
【问题描述】:
有两个文件: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(),我可以从回复中看到用户名。
我正在将此函数导入 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)
}
...
}
结果我进入了控制台user = undefined。 为什么我可以在 api.js 中看到数据,但在 RegistrationScreen.js 中看不到?
UPDATE_1
如果在 RegistrationScreen.js 中执行 console.warn(this.props.fetchAllUsers),我看到了函数代码,因此函数可见。
【问题讨论】:
-
您是否从 fetch 函数返回响应?您可能想尝试在 then 中返回 res.json()。
-
你需要
return承诺即export const fetchAllUsers = () => { return fetch(`http://${localIP}:${port}/api/userData`) ..... }
标签: javascript reactjs react-native fetch