簡體   English   中英

默認參數是否在babeljs / reactjs中作為對象注入?

[英]Default parameters are injected as object in babeljs/reactjs?

我的使用babeljs的reactjs設置如下所示

在此處輸入圖片說明

我的action.js

export function onIncrement() {
  return {
    type: 'INCREMENT'
  };
}

export function onDecrement() {
  return {
    type: 'DECREMENT'
  };
}

容器/App.js

import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as CounterActions from '../actions';

    class App extends Component {
      render() {
        const { counter, actions } = this.props;
        return (
          <div>
            <p>
              Clicked: {counter} times
            </p>
            <p>
              <button onClick={actions.onIncrement}>
                +
              </button>
            </p>
            <p>
              <button onClick={actions.onDecrement}>
                -
              </button>
            </p>
          </div>
        );
      }
    }

    App.propTypes = {
      counter: PropTypes.number.isRequired,
      actions: PropTypes.object.isRequired
    };

    function mapStateToProps(count) {
      return {
        counter: count
      };
    }

    function mapDispatchToProps(dispatch) {
      return {
        actions: bindActionCreators(CounterActions, dispatch)
      };
    }

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

容器/root.js

import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';

import App from './App';

export default class Root extends Component {
  render() {
    const { store } = this.props;
    return (
      <Provider store={store}>
        <App />
      </Provider>
    );
  }
}

Root.propTypes = {
  store: PropTypes.object.isRequired
};

Reducer / index.js

export default function counter(count = 0, action) {
  console.log(count)  // this comes as object {}
  console.log(action) // initially it as { type: '@@INIT'}
  switch (action.type) {
    case 'INCREMENT':
      return count + 1;
    case 'DECREMENT':
      return count - 1;
    default:
      return count;
  }
}

存儲/配置Store.js

import { applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';

import rootReducer from '../reducers';

export default function configureStore(initialState = {}) {
  // thunkMiddleware to handle async actions in redux
  const middlewares = [thunkMiddleware];
  // chrome devtool extension
  let devtool;

  if (NODE_ENV === 'development') {
    // redux-logger to log the redux state events in window.console
    const logger = createLogger({
      duration: true
    });
    middlewares.push(logger);

    // devtools - redux-chrome extension
    devtool = window.devToolsExtension ? window.devToolsExtension() : undefined;
  }
  // store - combines reducers and enchancements to redux using middlewares
  const store = createStore(
    rootReducer,
    initialState,
    devtool,
    applyMiddleware(...middlewares)
  );
  // hot module replacement for only for reducers
  if (module.hot) {
    module.hot.accept('../reducers', () => {
      // default - as es6 to es5 transpile in babel make the module to export as
      // module.export = somemodule.default
      const nextRootReducer = require('../reducers').default;
      store.replaceReducer(nextRootReducer);
    });
  }
  return store;
}

我的main.js

import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';

import Root from './containers/Root';
import configureStore from './store/configureStore';

const initialState = window.__INITIAL_STATE__;

const store = configureStore(initialState);

render(
  ,
  document.getElementById('root')
);

我的Package.json

我的package.json

我正在使用webpack進行捆綁,而使用babel進行轉譯。

當我最初在上運行此應用程序時,出現以下錯誤,

錯誤

進一步調查這個問題,我找到了如下所示的轉碼

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = counter;
function counter() {
  var count = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
  var action = arguments[1];

  console.log(count, "count"); // this comes as object {}
  console.log(action, "action"); // initially it as { type: '@@INIT'}
  switch (action.type) {
    case 'INCREMENT':
      return count + 1;
    case 'DECREMENT':
      return count - 1;
    default:
      return count;
  }
}

我的問題是:

  1. 為什么將我的defualt參數作為對象{}注入?
  2. 這是通天塔問題嗎?
  3. 我在這里做錯什么了嗎?

上面的代碼僅在我將其更改為下面時有效,

export default function counter(count = 0, action) {
  console.log(count , "count")  // this comes as object {}
  console.log(action, "action") // initially it as { type: '@@INIT'}
  switch (action.type) {
    case 'INCREMENT':
      return count + 1;
    case 'DECREMENT':
      return count - 1;
    default:
      return 0;
  }
}

mapStateToProps函數中,您首先需要像這樣從Redux狀態提取count

function mapStateToProps(state) {
  return {
    counter: state.count
  };
}

未來:

空對象注入是由於我在configureStore.js中將initialState設置為= {},我將其更改為undefined,它就像一個魅力

import { applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';

import rootReducer from '../reducers';

export default function configureStore(initialState) {
  // thunkMiddleware to handle async actions in redux
  const middlewares = [thunkMiddleware];
  // chrome devtool extension
  let devtool;

  if (NODE_ENV === 'development') {
    // redux-logger to log the redux state events in window.console
    const logger = createLogger({
      duration: true
    });
    middlewares.push(logger);

    // devtools - redux-chrome extension
    devtool = window.devToolsExtension ? window.devToolsExtension() : undefined;
  }
  // store - combines reducers and enchancements to redux using middlewares
  const store = createStore(
    rootReducer,
    initialState,
    devtool,
    applyMiddleware(...middlewares)
  );
  // hot module replacement for only for reducers
  if (module.hot) {
    module.hot.accept('../reducers', () => {
      // default - as es6 to es5 transpile in babel make the module to export as
      // module.export = somemodule.default
      const nextRootReducer = require('../reducers').default;
      store.replaceReducer(nextRootReducer);
    });
  }
  return store;
}

有關更多詳細信息: https : //github.com/reactjs/redux/issues/1502#issuecomment-194151490

檢查您的configureStore函數:

export default function configureStore(initialState = {}) {
  // ...
}

您將initialState設置為{} ,因此,如果undefined window.__INITIAL_STATE__ ,您將獲得{}作為減速器的初始狀態。 嘗試將其更改為:

export default function configureStore(initialState = 0) {
  // ...
}

babel輸出沒有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM