【问题标题】:undefined is not an object (evaluating 'this.refs.loaderRef.hide')undefined 不是一个对象(评估 'this.refs.loaderRef.hide')
【发布时间】:2019-02-04 00:27:23
【问题描述】:

这是我的商店课程
.........
从'./utils/Loader'导入Loade; 导出默认类存储扩展组件 {

.................
render() {

        return (
           <View style={{ flex: 1, backgroundColor: "white" }}>
             <Loader ref={"loaderRef"}/>
    ...........................

当我从我的商店课程中拨打 this.refs.loaderRef.hide();

遇到这样的错误 undefined 不是对象(评估 'this.refs.loaderRef.hide')

我是 react native 的新手,谁能帮帮我?

【问题讨论】:

  • 什么时候出现这个错误?点击某个功能?
  • 响应发布请求..... .then((response) => response.json()) .then(async (responseJson) => { this.refs.loaderRef.hide (); }
  • 能否再添加一些代码?
  • await fetch('' + aws_data.path + aws_data.stage + aws_lamda.contentmanagement, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Authorization':acceestoken }, body: JSON.stringify(reqobj), }).then((response) =&gt; response.json()) .then(async (responseJson) =&gt; { ...... }) this.refs.loaderRef.hide(); }) .catch((error) =&gt; { this.refs.loaderRef.hide(); console.error(error); });

标签: react-native ref


【解决方案1】:

它的范围问题。

_this声明this

let _this = this; //before api call

然后使用

_this.refs.loaderRef.hide

【讨论】:

    【解决方案2】:

    这只是意味着loaderRef 为空,请检查您是否正确初始化loaderRef

    还要检查,this 将在您调用生命周期方法时返回当前组件上下文,例如在 render() / componentWillMount() 中。但是如果你从你的方法中调用this,它将返回当前的方法实例。

    如果这是个问题,那么您可以创建一个全局命名为 _this 的变量,并在 render()constructor 中初始化,如 _this = this;。然后像_this.refs.loaderRef.hide();一样使用它

    例如

    var _this;
    export default class ScreenMyProfile extends Component {
        constructor(props) {
         super(props);
         _this = this;
        }
    }
    

    【讨论】:

    • 我在哪里声明_this?在课程开始时?(抱歉问了一些愚蠢的任务,我对此完全陌生)
    • 在调用 await fetch 之前声明
    • @ben10 请参阅答案中的示例
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2022-09-22
    • 1970-01-01
    • 2018-11-12
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多