【问题标题】:Redux + React-router component not renderingRedux + React-router 组件不渲染
【发布时间】:2015-09-07 21:19:08
【问题描述】:

所以我试图用Redux 配置React-router 我已经使用this example 来设置一个基本的应用程序。

当我尝试渲染我的组件时,我收到 1 个错误和 2 个警告。

错误是:Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

警告 #1:Warning: React.createElement: type should not be null or undefined. It should be a string (for DOM elements) or a ReactClass (for composite components).

警告 #2:Warning: Only functions or strings can be mounted as React components.

我刚刚得到了两个简单的组件。一个Root 组件和一个Container 组件来测试一切是否正常。

Root 组件的内容:

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createHistory } from 'history';
import { createStore, combineReducers } from 'redux';
import { Router, Route } from 'react-router';
import timeline from '../reducers/timeline';

import Container from '../components/Container';

const store = createStore(combineReducers({timeline}));

store.subscribe(() => {
  console.info(store.getState());
})

const history = createHistory();

React.render(
  <Provider store={store}>
    {() =>
      <Router history={history}>
        <Route path="/" component={Container}/>
      </Router>
    }
  </Provider>,
  document.getElementById('root')
);

Container组件的内容:

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

class Container extends Component {
  render() {
    return (
      <div id="outter">
        Container
      </div>
    );
  }
}

function mapStateToProps(state) {
  console.log(state);

  return {
    test: state,
  };
}

export default connect(
  mapStateToProps,
  {
    type: 'TEST_ACTION',
  }
)(Container);

以防万一——reducer 的内容也是如此:

const initialState = [
  {id: 1, message: 'Test message'},
];

export default function timeline(state = initialState, action = {}) {
  switch (action.type) {
    case 'TEST_ACTION':
      return initialState;
    default:
      return state;
  }
}

【问题讨论】:

    标签: javascript reactjs react-router redux


    【解决方案1】:

    我可以看到的一个问题是您传递给Container 组件中的connect 函数的第二个参数。您正在传递一个对象。根据the documentation,如果您传递一个对象,它将期望该对象的属性是动作创建者(它们是函数)。所以它可能看起来像这样:

    export default connect(
      mapStateToProps,
      {
        test: () => { type: 'TEST_ACTION' }
      }
    )(Container);
    

    然后,这将为您的 props 添加一个名为 test 的属性,您可以调用该函数来调度测试操作。

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 2016-02-22
      • 2019-07-14
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多