2017-08-24 79 views
0

這是一個簡單的組件,它顯示一個計數器和兩個按鈕來遞增/遞減它。在mapStateToProps中應用參數

class App extends Component { 
    render() { 
    return (
     <div className="App"> 
     <h1>{this.props.counter}</h1> 
     <button type="button" onClick={this.props.increment}> 
      increment 
     </button> 
     <button type="button" onClick={this.props.decrement}> 
      decrement 
     </button> 
     </div> 
    ); 
    }  
} 

const mapStateToProps = state => ({ 
    counter: state.counter 
}); 

const mapDispatchToProps = dispatch => ({ 
    increment:() => dispatch({ type: "INCREMENT" }), 
    decrement:() => dispatch({ type: "DECREMENT" }) 
}); 

App.propTypes = { 
    counter: PropTypes.number.isRequired, 
    increment: PropTypes.func.isRequired, 
    decrement: PropTypes.func.isRequired 
}; 

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

這是一個很小的例子,但在現實生活中,我需要在mapStateToProps很多道具,所有需要state ARG。我正在嘗試將state arg應用於對象返回中的所有值mapStateToProps。事情是這樣的:

const mapStateToProps = state => ({ 
    user: getCurrentUser(state), 
    page: getPage(state), 
    // ... f(state) 
}); 

我試了一下:

const mapStateToProps = state => 
    _.mapValues(
    { 
     counter: state => state.counter 
    }, 
    state 
); 

我得到這個錯誤:proxyConsole.js:56 Warning: Failed prop type: Invalid prop計數器of type布爾supplied to 'App', expected 'number'. 我在做什麼錯?

+1

爲什麼我的老闆不會讓我在ClojureScript中編碼? – qleguennec

回答

1

錯誤說counterboolean和你希望一個number。正如您在代碼底部看到的那樣,指定了propTypes

App.propTypes = { 
    counter: PropTypes.number.isRequired, 
    increment: PropTypes.func.isRequired, 
    decrement: PropTypes.func.isRequired 
}; 

確保counternumber

+0

是的。代碼在第一個版本中運行良好。 – qleguennec