基于类的组件中的dispatch()方法

时间:2018-05-14 13:13:43

标签: reactjs redux react-redux

我是React / Redux绑定的新手,我将用刷新笑话的形式实现Redux组件,可能会改变获取的笑话数量(默认情况下是1个笑话):

      import fetchJokes from '../actions/jokes';
      import { connect } from 'react-redux';

      class FormToRefresh extends React.Component {
        constructor(props) {
          super(props);
          this.state = {value: 1};
          this.handleInput = this.handleInput.bind(this);
          this.handleSubmit = this.handleSubmit.bind(this);
        }

        handleInput(e) {
          let input = e.target.value;
          if(isNaN(input)||input > 10||input< 1) {
            alert("Wrong input");
            this.setState({value: 1}); 
          } else {
            this.setState({value: input})     
          }

          handleSubmit(e) {
            // this should trigger dispatching fetchJokes action
            // but how to integrate dispatch() function here...                

            dispatch(fetchJokes(this.state.value));

          }

          render() {
            return (
              <div>
                <form onSubmit={this.handleSubmit>
                  <label>Enter amount of jokes (from 1 to 10):
                    <input type="text" value={this.state.value} onInput={this.handleInput} />
                  </label>
                  <button type="submit">Refresh</button>
                </form>  
              </div>)
            } 
          }

         export default connect()(FormToRefresh);

通常,我会查看指南https://redux.js.org/basics/usage-with-react#implementing-other-components,我倾向于实现基于类的组件而不是基于函数的组件。我对如何将 dispatch()方法集成到guide的AddTodo函数中有一些误解,我应该如何在FormToRefresh类中实现它?如果您发现任何其他错误,请告诉我。

1 个答案:

答案 0 :(得分:0)

当您未通过mapDispatchToProps时,连接功能会将dispatch作为组件的支柱使用,因此您可以使用

// bind the below function 
handleSubmit  = (e)  => { 
    const { dispatch } = this.props;                
    dispatch(fetchJokes(this.state.value));
}

将操作传递给连接,如

// bind the below function 
handleSubmit  = (e)  => { 
    const { fetchJokes } = this.props;                
    fetchJokes(this.state.value);
}

export default connect(null, { fetchJokes })(FormToRefresh);