【发布时间】:2019-10-27 18:33:38
【问题描述】:
我有一个从 json 文件中获取数据的外部函数,我想为我的组件使用这个函数来获取问题数据,我该如何管理它才能工作?
这是我尝试过的,但它不起作用:
组件:
screens/QuizzQuestion.js
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button} from 'react-native';
import { getQuestionData } from '../utils/utils'
export default class QuizzQuestion extends Component {
constructor(props) {
super(props);
this.state = {
info:null
};
}
loadData(){
getQuestionData(2).then(data=>{
this.setState({ info: data })
});
}
componentDidMount() {
this.loadData();
}
外部功能:
/utils/utils.js
import * as data from "../assets/questions/questions.json";
export function getQuestionData(n){
return data.questions[n];
}
我每次都有这个错误:
TypeError: TypeError: (0, _utils.getQuestionData)(0).then 不是函数。 (在 '(0, _utils.getQuestionData)(0).then(function (data) { _this2.setState({ 信息:数据 }); })', '(0, _utils.getQuestionData)(0).then' 未定义) * 屏幕\QuizzQuestion.js:20:28 在 loadData * screen\QuizzQuestion.js:26:4 在 componentDidMount - node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:15036:10 在 commitLifeCycles - node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:16636:8 在 commitAllLifeCycles - ... 来自框架内部的另外 18 个堆栈帧
【问题讨论】:
-
getQuestionData没有返回承诺,但您尝试像它一样使用它。 -
loadData(){ this.setState({ info: getQuestionData(2) }); }
标签: javascript reactjs react-native ecmascript-6