2017-08-31 120 views
1

我第一次mapDispatchToProps反应过来的时候就没有定义事件监听终极版的道具和我想要一个简单的动作addClick绑定到“click”事件,但是当我点击我收到的错误:使用反应/终极版使用

Uncaught TypeError: Cannot read property 'props' of undefined

我(精简)的代码是:

import {addClick} from './actions' 
const mapDispatchToProps = {addClick} 
class App extends Component { 
    componentDidMount() { 
     document.addEventListener('click', this.props.addClick) 
    } 
    componentWillUnmount() { 
     document.removeEventListener('click', this.props.addClick) 
    } 
} 
export default connect(mapStateToProps, mapDispatchToProps)(App) 

我以前用它在构造函数中类和绑定中定义为this行动的创建者实现,而不mapDispatchToProps。但我认为mapDispatchToProps点的一部分是绑定动作创建者this(以及包装它在dispatch

我错过了什么?

谢谢!

+0

您可以将代码添加到您的动作创建者addClick吗?你在addClick中使用“this”吗? – jonahe

+0

哇,我真笨!当我定义它并将其绑定到类中时,我在之前的动作中使用了'this.props'。 – Taaam

+0

呵呵,它发生在最好的状态(并且会再次发生);) – jonahe

回答

1

你使用道具里面的addClick动作吗?

检查这个例子:

import React from "react"; 
import { render } from "react-dom"; 
import { connect, Provider } from "react-redux"; 
import { createStore } from "redux"; 

function addClick(event) { 
    return { 
    type: "CLICK", 
    payload: `pageX: ${event.pageX} | pageY: ${event.pageY}` 
    }; 
} 

const mapStateToProps = state => { 
    return { 
    clickXY: state 
    }; 
}; 
const mapDispatchToProps = { addClick }; 

class App extends React.Component { 
    componentDidMount() { 
    document.addEventListener("click", this.props.addClick); 
    } 
    componentWillUnmount() { 
    document.removeEventListener("click", this.props.addClick); 
    } 
    render() { 
    return (
     <h1> 
     Click message: {this.props.clickXY} 
     </h1> 
    ); 
    } 
} 

function clickReducer(state = "None", action) { 
    switch (action.type) { 
    case "CLICK": { 
     return action.payload; 
    } 
    default: 
     return state; 
    } 
} 

let store = createStore(clickReducer); 

const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App); 

class Root extends React.Component { 
    render() { 
    return (
     <Provider store={store}> 
     <AppContainer /> 
     </Provider> 
    ); 
    } 
} 

render(<Root />, document.getElementById("root")); 

链接editor

所以绑定的作品以及在此代码。你能分享addClick方法的代码吗?

1

从文档中我可以看出,用于mapDispatchToProps的short_hand(const mapDispatchToProps = {addClick})对象不会将this与任何东西绑定。它只是看到你的addClick动作创建者被派遣调用。因此,如果您在组件中执行addClick(3),那么这将导致看起来像这样的电话dispatch(addClick(3))

我不确定为什么你的动作创建者需要访问this。难道你不能把它作为参数需要的数据传递给它吗?因此,您的组件中的呼叫可能看起来像

componentDidMount() { 
     const {addClick, someOtherProp} = this.props; 
     document.addEventListener('click',() => addClick(someOtherProp)); 
    } 
相关问题