redux-react中的调度函数

Quo*_*ran 24 javascript ecmascript-6 reactjs react-redux

我正在研究反应,我有一个这样的例子

//index.js
const store = createStore(reducer)
render(
  <Provider store={store}>
    <AddTodo />
  </Provider>,
  document.getElementById('root')
)

//Apptodo.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'

let AddTodo = ({ dispatch }) => {
  let input

  return (
    <div>
      <form onSubmit={e => {
        e.preventDefault()
        if (!input.value.trim()) {
          return
        }
        dispatch(addTodo(input.value))
        input.value = ''
      }}>
    .......
Run Code Online (Sandbox Code Playgroud)

为什么不能得到this.pros.store,只需调用dispatch()函数?

编辑:它是如何提取dispatchthis.pros.不是对象this.pros.store吗?在这种情况下,为什么我们不提取store

谢谢.

Row*_*and 20

您的addTodo组件可以访问商店的状态和方法(例如,dispatch,getState等).因此,当您通过connect方法将React视图与Redux存储连接起来时,您可以访问存储的状态和方法.

({ dispatch })只是使用JS 解构赋值dispatchthis.props对象中提取.

  • 您无法提取商店。react-redux的[Provider](https://github.com/reactjs/react-redux/blob/master/docs/api.md)组件使整个redux存储可通过[连接](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options)方法。因此,该组件具有“商店”的方法,并且状态被合并到其道具中。要访问`dispatch`,它可以通过`this.props.dispatch`访问它。 (2认同)

jab*_*tta 19

react-redux是将这些方法作为props传递给组件的库.

dispatch()是用于分派操作和触发状态更改到商店的方法.react-redux只是试图让您方便地访问它.

但请注意,如果您将操作传递给connect函数,则不能在props上使用调度.换句话说,在下面的代码中,由于我正在传递someAction连接,dispatch()因此不再提供道具.

然而,这种方法的好处是你现在可以在你的道具上使用"连接"动作,当你调用它时会自动为你调度.

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { someAction } from '../myActions';

const MyComponent = (props) => {
  // someAction is automatically dispatched for you
  // there is no need to call dispatch(props.someAction());
  props.someAction();
};

export default connect(null, { someAction })(MyComponent);
Run Code Online (Sandbox Code Playgroud)

或者,如果我们使用对象解构,如示例所示,您给出...

const MyComponent = ({ someAction }) => {
  someAction();
};
Run Code Online (Sandbox Code Playgroud)

但是,重要的是要注意,您必须调用props上可用的连接操作.如果你试图调用someAction(),你将调用原始的导入动作 - 而不是在props上可用的连接动作.下面给出的示例不会更新商店.

const MyComponent = (props) => {
  // we never destructured someAction off of props
  // and we're not invoking props.someAction
  // that means we're invoking the raw action that was originally imported
  // this raw action is not connected, and won't be automatically dispatched
  someAction();
};
Run Code Online (Sandbox Code Playgroud)

这是人们在使用react-redux时遇到的常见错误.遵循eslint的无影子规则可以帮助您避免这个陷阱.