1

下午好!我开始处理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);

4

1 回答 1

2

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

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

// 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" })
}

此外,使用动作创建者可能更容易/更好。

// 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

于 2020-01-28T10:27:42.657 回答