2017-05-02 43 views
1

我應該通過在mapDispatchToProps參數(在地方「????????」是)Redux mapDispatch ToProps。我應該通過哪些數據作爲參數?

我的行爲是在這裏:

function addTodo(text) { 
    return { 
     type: 'ADD_TODO', 
     text: text 

    } 
} 
export default addTodo 

這是我的組件/容器這裏我使用mapDispachToProps(){}和mapStateToProps(){}

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

class TodoInput extends Component { 

    constructor(props) { 
     super(props) 
     this.state = { 
      inputValue: '' 
     } 
    } 

    onChangeHandle(event) { 
    this.setState({ 
     inputValue: event.target.value 
    }) 
    } 

    handleSubmit(event) { 

    event.preventDefault() 
    //this.props.dispatch(addTodo(this.state.inputValue)) 
    this.props.buttonClick(this.state.inputValue) 
    } 

    render() { 
    return (
     <div> 

      <input 
      type = "text" 
      value = {this.state.inputValue} 
      onChange = {this.onChangeHandle.bind(this)} 
      /> 
      <button onClick={this.handleSubmit.bind(this)}>Submit</button> 
     </div> 
    ); 
    } 
} 

const mapStateToProps = (state) => { 
    return state 
} 

const mapDispatchToProps = (dispatch) => { 
    return { 
    buttonClick:() => dispatch(addTodo(???????????)) 
    } 
} 


export default connect(mapStateToProps, mapDispatchToProps)(TodoInput); 

回答

2

你必須通過與inputValue的任何名稱,在這種情況下,參數 「todoText」。

const mapDispatchToProps = (dispatch) => { 
    return { 
    buttonClick: (todoText) => dispatch(addTodo(todoText)) 
    } 
} 
+1

這麼簡單:)謝謝:) – Lukas

+0

最歡迎的。 –

1

您使用buttonClick像:this.props.buttonClick(this.state.inputValue)

煥你寫mapDispatchToProps,要定義屬性(功能),其使用派遣。

對於你的代碼mapDispatchToProps應該是:

const mapDispatchToProps = (dispatch) => { 
    return { 
    buttonClick: (text) => dispatch(addTodo(text)) 
    } 
} 
相關問題