【问题标题】:TypeError: null is not an object (evaluating 'prevState.intervalTimer')TypeError:null 不是对象(评估“prevState.intervalTimer”)
【发布时间】:2021-05-26 19:27:19
【问题描述】:

我的 expo 应用程序在与 prettier 发生冲突后停止了。我拉了一个新分支,禁用了 vscode 上的任何代码格式化,即使npm install 现在需要--legacy-peer-deps 才能工作,事情开始一一得到修复。现在它给出了一个错误代码TypeError: null is not an object (evaluating 'prevState.intervalTimer'),我似乎无法弄清楚它为什么会抛出这个错误。

这是我使用'prevState.intervalTimer')的地方(在我的主屏幕上)

  componentDidUpdate ( prevProps, prevState )
  {
    const name = ( this.props.currentWorkoutPlan || {} ).name;
    const prevName = ( prevProps.currentWorkoutPlan || {} ).name;
    if ( name !== prevName )
    {
      this.props.navigation.setParams( { currentWorkoutPlanName: name } );
    }

    if ((prevState.intervalTimer || {}).rest_time === this.props.rest_time) {
      !!this.horizRef.current && this.horizRef.current.scrollTo({ animated: false, x: 0, y: 0 });
    }
  }

我的代码中没有其他地方有prevState.intervalTimer

我的interval timer 减速器的一部分是这样的:

    case TIMER.START_REST_TIMER: {
      const { initialTime, exercise } = action.payload;
      return {
        ...state,
        initial_rest_time: initialTime,
        rest_time: initialTime,
        rest_exercise: exercise
      }
    }
    case TIMER.TICK_REST_TIMER: {
      return {
          ...state,
          rest_time: state.rest_time - 1
      }
    }
    case TIMER.STOP_REST_TIMER: {
      return {
        ...state,
        rest_time: state.initial_rest_time,
        initial_rest_time: null,
        rest_exercise: null
      }
    }
    default:
      return state;
  }
};

export default intervalTimer;

我通过mapStateToProps导入了它

const mapStateToProps = ( state ) => ( {
  rest_time: state.intervalTimer.rest_time,
  rest_exercise: state.intervalTimer.rest_exercise
} );

所有这些代码都保持不变,我将它们与我的旧代码进行了比较,我不知道为什么会失败,但这是向我抛出的错误。

【问题讨论】:

    标签: javascript reactjs react-native redux expo


    【解决方案1】:

    它最初为 null,因此您可以使用可选的链接运算符来处理它。

    if ((prevState?.intervalTimer || {}).rest_time === this.props.rest_time) {
          !!this.horizRef.current && this.horizRef.current.scrollTo({ animated: false, x: 0, y: 0 });
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-13
      • 2020-11-21
      • 2021-05-27
      • 2021-12-29
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多