【问题标题】:Default parameters are injected as object in babeljs/reactjs?默认参数作为 babeljs/reactjs 中的对象注入?
【发布时间】:2016-06-22 18:16:00
【问题描述】:

我使用 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;
  }
}

存储/configureStore.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')
);

我的包.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. 为什么我的默认参数被注入为 Object {} ?
  2. 这是 babel 问题吗?
  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;
  }
}

【问题讨论】:

    标签: javascript reactjs webpack babeljs


    【解决方案1】:

    检查您的configureStore 函数:

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

    您将initialState 设置为{},因此如果window.__INITIAL_STATE__undefined,您将获得{} 作为减速器的初始状态。 尝试将其更改为:

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

    babel 输出没有问题。

    【讨论】:

      【解决方案2】:

      在您的mapStateToProps 函数中,您首先需要从 Redux 状态中提取 count,如下所示:

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

      【讨论】:

      • 我现在不在我的电脑附近。无论如何,这怎么可能?使用 state.count 有什么用?我认为这行不通。在我的代码中,如果您在 mapStateToProps 中打印 count ,它将显示为 Object {},这个 state,count 怎么会起作用?请解释一下?
      • 嗨,这不起作用...我在输入 console.log(state.count) 时变得不确定
      • 请阅读 react-redux 的文档,而不是对我投反对票。这可能不是主要错误,但我认为您误解了如何收听 Redux 商店更新:@ 987654321@ in @ 987654325@ 您正在处理整个 redux 存储,而不仅仅是您期望的 count 值。
      • 你看到我上面发布的答案了吗?当我使用 combineReducer 方法组合多个减速器时,您所说的是正确的。这是一个单一的减速器,我没有使用组合减速器,如上面的代码所示。我认为您还需要再次阅读文档:)。
      【解决方案3】:

      未来:

      空对象注入是由于我在 configureStore.js 中将 initialState 设置为 = {},我将其更改为未定义,它就像一个魅力

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-15
        • 2014-08-18
        • 2021-09-23
        • 1970-01-01
        • 2014-06-12
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多