首页 > 解决方案 > 为什么在 react-redux 上未定义 [object Object],[object Object]?

问题描述

我有一个:

classesAll:[0:{id:1,title:'test1'},1:{id:2,title:'test2'}]

当我将它“console.log(this.props.classes.classesAll)”到控制台时,它不会返回我的数组的异常值。相反,它显示以下内容: undefined [object Object],[object Object]


async componentDidMount() {
    await this.props.showAllClasses();
    console.log("***", this.props.classes.classesAll)
  }
Redux action:

export const showAllClasses = () => {
    return async dispatch => {
       dispatch(pageLoading(true));
            await  Api.get(`classes.php`).then(res => {
                //this.state.all = res.data;
                const classesAll = res.data.data;
                state.classesAll = classesAll;
            });
       await dispatch(onChangeClasessAll(state.classesAll));
       dispatch(pageLoading(false));
        };

    };

    export const onChangeClasessAll = classesAll => {
        const type =  CLASSES_ALL;
         return   { type , classesAll};
      };

图片

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


因为您的请求是异步的。您应该在请求返回时对其进行控制台。在 react-native 0.6 中,您可以在 getDerivedStateFromProps(props, state) 方法中执行此操作

static getDerivedStateFromProps(props, state) {
    console.log(props.classes.classesAll)
}

在 react-native 0.6 之前,你应该在 componentWillReceiveProps() 方法中进行

componentWillReceiveProps(nextProps) {
 console.log(props.classes.classesAll)
}

推荐阅读