【问题标题】:react-redux, onClick does not launch action function(undefined)react-redux, onClick 不启动动作函数(未定义)
【发布时间】:2017-05-07 21:40:14
【问题描述】:

我正在尝试在按下按钮时使用 react-redux 发出 ajax 请求,但是当 onClick 操作尝试从操作组件启动功能时出现错误。

post_data.js

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import getPostsData from '../actions/index';

class PostButton extends Component{

constructor(props){
    super(props);

    this.GetPostData = this.GetPostData.bind(this);
}

GetPostData(event){
    event.preventDefault();
    this.props.getPostsData();  
} 

render(){
    return(
        <div style={{marginTop: 50 + 'px'}}>
                <button className="btn btn-success" onClick={this.GetPostData}>Click Here to Load Posts</button>
        </div>
    )
  }
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({getPostsData}, dispatch);
}

export default connect(null, mapDispatchToProps)(PostButton);

行动:

import axios from 'axios';

export const GET_POSTS_DATA = 'GET_POSTS_DATA';

export function getPostsData() {
   const url = `https://jsonplaceholder.typicode.com/posts`;

   const request = axios.get(url);
   console.log(request);

   return{
      type: GET_POSTS_DATA,
      payload: request
   }
}

减速机:

 import GET_POSTS_DATA from '../actions/index';

 export default function(state = [], action){
    switch (action.type){

      case GET_POSTS_DATA:
        return [action.payload, ...state]
    }

    return state;
 }

控制台错误: 未捕获的 TypeError:this.props.getPostsData 不是函数 这与:

GetPostData(event){
    event.preventDefault();
    this.props.getPostsData();  
}

感谢任何帮助...

【问题讨论】:

    标签: javascript ajax reactjs redux react-redux


    【解决方案1】:

    您的 getPostsData 导入语句应该是:

    import {getPostsData} from '../actions/index';
    

    您使用的语法是指默认导出,据我在您的 sn-p 中可以看出,没有默认导出。

    【讨论】:

    • 谢谢你,尼克!:) 我知道这很愚蠢,而且它是:)))) 在我正确导入后就像魔法一样。
    【解决方案2】:

    可能只是一个错字:getPostsData 不是 PostButton 组件的属性,而是从 js 模块导入。

    直接致电getPostsData() 代替this.props.getPostsData()

    【讨论】:

    • 不,它应该是 this.props 的一部分,但由于某种原因它不是......无论如何,直接调用也不起作用。
    【解决方案3】:

    这是在您的情况下调用上述函数的正确方法:

    GetPostData(event){
       event.preventDefault();
       getPostsData();  
    } 
    

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      • 2023-04-10
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多