【问题标题】:dispatch is not defined no-undef调度未定义 no-undef
【发布时间】:2018-10-02 23:39:16
【问题描述】:

我是 redux 的新手,我正在尝试从函数内部调度一个动作,但它说“调度未定义 no-undef”。谁能告诉我我做错了什么

import React, { Component } from 'react';
import {connect} from 'react-redux';
import {getYear} from '../actions/getYearAction';
import {requestYear} from '../actions';

class SigninForm extends Component {

  constructor(props){
    super(props);
    this.state = {
      car :{
        year: '',
        brand:[],
      }
    }
  }

  getYear(){
    return this.props.year.map( (year, id) => {
      return(
        <option value={year} key={id}>{year}</option>
      )
    })
  }

    handleSelection(e){
      dispatch(requestYear( e.target.value ));
  }


  render() {
    return (
      <div>
        <form>
          <select onChange = {this.handleSelection.bind(this)}>
          <option value="" selected disabled hidden>--YEAR--</option>
          {this.getYear()}
          </select><br/>
          <select>
            <option value='' selected disabled>-Brand-</option>

          </select>
          <button type='submit'>Add</button>
          {this.props.value}
        </form>
      </div>
    );
  }
}

function mapStateToProps(state){
  return{
    year: state.year
  }
}
export default connect( mapStateToProps)(SigninForm);

我必须使用从 saga 中选择的年份进行 api 调用,但我不知道该怎么做。

这是我的行动

import { createAction } from 'redux-actions';

export const REQUEST_YEAR = 'REQUEST_YEAR';
export const requestYear = createAction(REQUEST_YEAR);

请帮帮我 谢谢

【问题讨论】:

    标签: reactjs redux react-redux redux-saga dispatch


    【解决方案1】:

    dispatch 和你的其他 props 一样是一个 props,你需要用 this.props.dispatch 调用它。

    另外,最好只传入你想要调用的动作作为道具:

    handleSelection(e) {
      this.props.requestYear( e.target.value );
    }
    
    ...
    
    export default connect( mapStateToProps, { requestYear })(SigninForm);
    

    【讨论】:

    • 非常感谢。你能告诉我在采取行动后我如何从 saga 中执行某事吗?
    • 你想执行什么? API 调用?这是 redux-saga 的主要用例,您可以查看文档。
    • 谢谢!添加 dispatch as this.props.dispatch() 解决了我的问题。
    猜你喜欢
    • 2021-10-16
    • 2018-06-09
    • 2018-10-02
    • 2021-05-26
    • 2021-06-17
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多