如何获得 dispatch redux

How to get dispatch redux

我正在学习 redux 和 React。我正在学习一些教程,以便制作一个应用程序。

我有这个action:

export function getDueDates(){
  return {
    type: 'getDueDate',
    todo
  }
}

这是商店:

import { createStore } from 'redux';
import duedates from './reducers/duedates'

export default createStore(duedates)

这是减速器:

从 'immutable'

导入不可变
export default (state = Immutable.List(['Code More!']), action) => {
  switch(action.type) {
    case 'getDueDate':
      return state.unshift(action.todo)
    default:
      return state
  }
}

entry point js 我有这个:

import React from 'react';
import ReactDOM from 'react-dom';

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

import App from './app/Components/AppComponent';


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

现在,(根据一些示例),我应该从 dispatch 调用 getDueDate 但我不知道如何在组件上获取 dispatch 来触发操作

这里缺少的部分是 react-redux 中的 connect 函数。此函数将 "connect" 您的组件存储到商店,并为其提供 dispatch 方法。具体如何做到这一点有多种变化,所以我建议阅读文档,但一个简单的方法是这样的:

// app/Components/AppComponent.js

import { connect } from 'react-redux';

export class App extends React.Component {

    /* ...you regular class stuff */

    render() {

        // todos are available as props here from the `mapStateToProps`
        const { todos, dispatch } = this.props;

        return <div> /* ... */ </div>;
    }
}

function mapStateToProps(state) {
    return {
        todos: state.todos
    };
}

// The default export is now the "connected" component
// You'll be provided the dispatch method as a prop
export default connect(mapStateToProps)(App);

使用 react-redux 包中的 connect。它有两个函数作为参数,mapStateToPropsmapDispatchToProps,你现在感兴趣。根据 Nick Ball 的部分正确回答,您将像这样导出:

export default connect(mapStateToProps, mapDispatchToProps)(App)

你的 mapDispatchToProps 看起来像这样:

function mapDispatchToProps (dispatch, ownProps) {
  return {
    getDueDate: dispatch(getDueDate(ownProps.id))
  }
}

只要连接到商店的组件具有从上方传递的 属性 id,您就可以从其中调用 this.props.getDueDate()

编辑:在这种情况下可能不需要使用 id,但是我的意思是指出道具作为第二个参数:)