2017-10-06 126 views
1

我尋找答案,這一個,但沒有看到任何匹配我的問題。我正嘗試使用React & Redux構建一個計算器應用程序,並且每當我單擊其中一個數字按鈕時,出現「this.props.AppendCharacter不是函數」的錯誤代碼陣營 - 終極版:this.props.AppendCharacter不是一個函數

這是我的相關代碼:

number_button.js

import React, {Component} from 'react'; 
import {bindActionCreators} from 'redux'; 
import {connect} from 'react-redux'; 

import AnswerScreen from '../containers/answer_screen'; 
import AppendCharacter from '../actions/index'; 

class NumberButton extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { button: '' }; 
     this.clickButton = this.clickButton.bind(this); 
    }; 

    clickButton() { 
     this.props.AppendCharacter(this.props.number); 
     console.log('clicked on ', this.props.number); 
     this.setState({ button: this.props.number }); 
    } 

    render(props) { 
     return (
      <div className="number-button general-button" onClick={this.clickButton}> 
      {this.props.number} 
      </div> 
     ); 
    }; 
}; 

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

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

動作/ index.js

export function AppendCharacter(character) { 
    return { 
     type: APPEND, 
     payload: character 
    }; 
}; 

回答

0

你可以完成你需要改變你的什麼到:

function mapDispatchToProps(dispatch) { 
    return { 
     AppendCharacter: (character) => dispatch(AppendCharacter(character)); 
    }; 
} 

我不熟悉bindActionCreators,所以別人可能需要如果你需要的功能來衡量英寸


備註:它看起來並不像您在當前設置中需要button的組件狀態。你可能有它的計劃,但在你的例子中沒有被使用。

+0

謝謝。我試過,但我得到了不同的錯誤,上面寫着「遺漏的類型錯誤:(0,_index2.default)不是一個函數」 (哦,我可能會當我得到這個工作,刪除該組件的狀態 - 在添加該部分後,我更改了設計。感謝您對此的評論。) – PirateJohn

+0

您近了。聽起來像這樣解決了你的問題。現在,你需要重新審視你如何導入和導出。聽起來你可能有(或沒有)'默認'出口,當你打算(或不意味着)。 [這應該幫助(https://stackoverflow.com/a/36796281/2479481) –

+1

原來'mapDispatchToProps'是確定的; 'bindActionCreators'在調用'dispatch()'時包裝動作創建者。我woud建議,雖然,如果不深刻地理解調度如何'()'的作品,因爲它增加了一個概念,一個潛在的混亂層,很多已經感到迷惑時,他們首先開始使用終極版,你不應該使用'bindActionCreators' 。 – stone

0
const mapDispatchToProps = { 
    AnswerScreen, 
    AppendCharacter 
}; 

export default connect(null, mapDispatchToProps)(NumberButton); 
+0

謝謝。我試過你的代碼,但不幸的是它仍然無法工作。 – PirateJohn

+0

這是朝正確方向邁出的一步,但它不會工作,因爲它實際上並沒有將派遣映射到道具。 'mapDispatchToProps'需要一個參數'dispatch'並返回爲每個動作創建者調用'dispatch'的函數。以我的答案爲例,說明一種設置方法。 –

0

嗯,我發現了錯誤。有人在不同的網站幫助我。 bindActionCreators工作正常,但問題是,當我從../actions/index中導入AppendCharacter時,我需要將AppendCharacter包裝在大括號中。我改變了,現在應用程序的作品。

Whe!

謝謝大家對您的回覆。這幾天我學到了很多東西!