繁体   English   中英

尝试运行时出现“TypeError:无法获取未定义或 null 参考的属性‘年龄’”

[英]Getting “TypeError: Unable to get property 'age' of undefined or null reference” when I try to run

如果分别单击 ADD 按钮或 SUBTRACT 按钮,我的应用程序应该只是增加年龄(初始化为 20)或减少年龄。

我不明白为什么我不断收到此错误。 我签入 reducer.js 以确保相应地使用“年龄”属性初始化 state,所以我完全不知道可能导致这种情况的原因。 我仔细检查了所有正确的依赖项,并确保所有语法都正确。

我认为可能导致它的另一件事是我没有在 reducer.js 中使用扩展运算符作为代码行const newState = {state} 出于某种原因,vscode 不允许我使用扩展运算符。 每次我执行并运行我的应用程序时,屏幕上都不会出现任何内容。 是否需要安装依赖项才能使用扩展运算符?

以下是我的代码:

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

import reducer from './reducer';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

const store = createStore(reducer);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

// 应用程序.js

import React from 'react';
import './App.css';
import { connect } from 'react-redux';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <div>Age: <span>{this.props.age}</span></div>
        <button onClick={this.props.onAgeUp}>Add</button>
        <button onClick={this.props.onAgeDown}>Sub</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return { age: state.age };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onAgeUp: () => dispatch({ type: 'ADD' }),
    onAgeDown: () => dispatch({ type: 'SUBTRACT' })

  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

// 减速器.js

import { ADD, SUBTRACT } from './actionTypes';

const initialState = {
  age: 20
};

const reducer = (state=initialState, action) => {
    const newState = {state};

    switch(action.type) {
        case ADD:
            newState.age+=1;
            break;
        case SUBTRACT:
            newState.age-=1;
            break;
        default:
            return state;
    }

};

export default reducer;

快速修复,您可以使用Object.assign代替传播运算符:

const newState = Object.assign({}, state);

要使用扩展运算符,您必须检查几件事:

首先确保@babel/plugin-proposal-object-rest-spread依赖项在package.json中,然后将其添加到 babel 配置文件的插件中:

{
  "plugins": ["@babel/plugin-proposal-object-rest-spread"]
}

欲了解更多信息,请访问babel rest 传播

我在这里看到三个问题:

  • 您将 newState 声明为 {state}。 这将在 object 中创建 object。
  • 由于您使用 const 声明 newState,因此无法更改。 但是你在这两种情况下都试图改变 newState 。
  • 您不会向 state 返还任何东西。 redux 的主要思想是通过返回新的 state 来更新 state。

newState 看起来像你定义它的方式:

{
  state: {
    age: 20
  }
}

这就是年龄未定义的原因,它不是直接子属性。

例如:

const letters = { alpha: 'a' }

const spreadLetters = { letters }

spreadLetters 将是一个新的 object,具有一个属性“字母”。 此属性的值将是原始字母变量的精确副本。

{
  letters: {
    alpha: a
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM