如何将访问方法 dispatch() 获取到 class 的组件中

how to get access method dispatch() into component of class

下午好!我开始处理 react-redux 并一度陷入困境。我不知道如何访问组件本身内部的 dispatch 方法。问题是,我正在尝试从表单字段中获取数据。在mapDispatchToProps方法中,我无法得到refs。请告诉我如何正确执行此操作?

例如: index.js

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

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

import App from './App'

const rootElement = document.getElementById('root')
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
)

代码是在这里输入的,可能是语法错误... App.js

// imports ...
class App extends React.Component {
  constructor(props) {
    super(props);
    this.title = React.createRef();
    this.message = React.createRef();
  }

  // Idea 1
  onSubmitHandler_1 = e => {
    e.preventDefault();
    // how get store.dispatch({type:"UPDATE", this.title.current.value, this.message.current.value});
  };

  render() {
    return (
      <form onSubmit={this.props.onSubmitHandler_1 OR this.onSubmitHandler_2}>
        <input type="text" ref={this.title} name="title" />
        <input type="password" ref={this.message} name="password" />
        <button>Send</button>
      </form>
    );
  }
}

const mapDispatchToProps = (state, ownProps) => {
  return {};
};

// Idea 1;
const mapDispacthTOProps = (dispatch, ownProps) => {
  return {
    onSubmitHandler_2: e => {
      e.preventDefault();
      // oh... no!!! bad idea...
      // let inputTitle = e.target.querySelector('[name="title"]');
      // let inputTitle = e.target.querySelector('[name="password"]')
      dispatch({ type: "UPDATE" }); //... ???? refs
      // how get access to fields or refs??
    }
  };
};

export default connect(mapDispatchToProps, mapDispacthTOProps)(App);

如果您不使用 mapDispatchToProps,则不应向 connect 函数传递任何内容。通过这种方式,dispatch 函数作为 prop 提供给您的组件。

因此,如果您像这样导出组件

// First one is 'mapStateToProps', not 'mapDispatchToProps' like in your code
export default connect(mapStateToProps)(App)

您可以在提交处理程序中使用 this.props.dispatch。所以,像

onSubmitHandler = (event) => {
  this.props.dispatch({ type: "SOME_ACTION", foo: "bar" })
}

此外,可能 easier/better 使用动作创建器。

// In some actions.js file or something
export const updateSomething = (data) => {
  return {
    type: "UPDATE",
    payload: data,
    // OR map specific attributes from the data object
  }
}

// In your component
import { updateSomething } from './actions.js'

class App extends React.Component {
  // .. all other code .. 

  submitHandler = (event) => {
    // These values would probably also be better in state variables
    const data = {
      title: this.title.current.value,
      message: this.message.current.value
    }
    this.props.updateSomething(data)
  }
}

const mapDispatchToProps = {
  updateSomething,
}

export default connect(mapStateToProps, mapDispatchToProps)(App)


如果你想映射几个函数并且也在你的组件中使用调度函数你可以这样做:https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-the-mapdispatchtoprops-function-with-bindactioncreators