【问题标题】:Dispatch function in React-ReduxReact-Redux 中的调度函数
【发布时间】:2017-08-09 19:33:21
【问题描述】:

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

//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 = ''
      }}>
    .......

为什么没有得到this.pros.store而只是调用dispatch()函数?

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

谢谢。

【问题讨论】:

  • 我相信您将 React 和 Redux 的概念混为一谈。 Props 是你从 React 组件中得到的。 Redux store 没有任何关系。 react-redux 将它们连接起来,使您可以更轻松地使用 Redux 的 store 方法 dispatch() 调度操作。 react-redux 还可以通过将函数作为第一个参数传递给 connect() 来使 store 的状态作为 props 可用。查看 react-redux 文档以获取更多信息。

标签: javascript reactjs ecmascript-6 react-redux


【解决方案1】:

react-redux is the library 将这些方法作为道具传递给您的组件。

dispatch() is the method used to dispatch actions 并触发存储的状态更改。 react-redux 只是想让你方便地访问它。

但是请注意,如果您确实将操作传递给您的连接函数,则该分派在道具上不可用。换句话说,在下面的代码中,由于我通过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);

或者如果我们要使用object destructuring,如您提供的示例中所示......

const MyComponent = ({ someAction }) => {
  someAction();
};

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

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();
};

这是人们在使用 react-redux 时经常遇到的一个常见错误。 Following eslint's no-shadow rule 可以帮助您避免这个陷阱。

【讨论】:

  • const MyComponent = ({ someAction ) =&gt; { 中缺少“}”?
【解决方案2】:

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

({ dispatch }) 只是使用JS destructuring assignmentthis.props 对象中提取dispatch

【讨论】:

  • 谢谢,我会读到这个,但是为什么我们要提取 dispatch 呢?提取商店还不够吗?
  • 您无法提取商店。 react-redux 的 Provider 组件通过 connect 方法使整个 redux 存储可用于下面层次结构中的组件。因此,该组件将 store's 方法和状态合并到其 props 中。要访问dispatch,可以通过this.props.dispatch访问。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 2020-08-09
  • 2021-02-23
相关资源
最近更新 更多