为什么我的状态没有正确映射到Redux中的道具?

时间:2017-06-16 03:25:46

标签: reactjs react-redux

我创建了这个组件:

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

export class Todos extends Component {
  render() {
    //todo remove
    console.log('testing this.props.todos', this.props.todos);

    //todo remove
    debugger;

    return (
      <div>hello from todos</div>
    );
  }
}

const mapStateToProps = function (store) {
  return {
      todos: store.todos
  }
}

export default connect(mapStateToProps)(Todos)

我正在使用Redux,这是reducer:

const initialState = {
  todos: [
    {
      name:'first todo'
    }
  ]
}

const Todos = (state = initialState, action) => {
  switch (action.type) {
    case "ADD_TODO":
      var newState = Object.assign({}, state, {todos: [...state.todos, action.data]});
      return newState;
    default:
      //todo remove
      debugger;
      return state;
  }
}

export default Todos;

由于某种原因,this.props.todos未定义且我的状态未正确映射到我的道具。如何将Redux存储连接到我的组件?

1 个答案:

答案 0 :(得分:1)

问题是您没有正确地将商店传递给您的组件!如果您想使用connect将组件连接到全局状态,则必须使用<Provider>提供的react-redux组件。因此,首先您使用createStore创建商店,然后将其传递给提供商:

import store from './store.js';
import { Provider } from 'react-redux'; 

const App = () => (
  <Provider store={store}>
    <Todos />
  </Provider>
);

ReactDOM.render(
  <div className="container">
    <App />
  </div>
, document.getElementById('root'));

注意<Provider>如何用于提供商店并使其可用于connect次调用。此外,<Todos>不应该采取任何道具。另外,您的导入:

import { Todos } from './components/todos.jsx';

错了。您的todos.jsx,您正在将connect ed组件导出为默认导出:

export default connect(mapStateToProps)(Todos)

所以你必须导入默认值

import Todos from './components/todos.jsx';