• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

为什么在调度一个动作时我得到了`null`?

reactjs 来源:karolis2017 8次浏览
console.log(bankStore.getState().balance); 

当我记录这个,我得到0预期。为什么在调度一个动作时我得到了`null`?

然后我有传递道具<BankApp />组分(如我明白)容器:

const mapStateToProps = state => { 
    return { 
    balance: state.balance 
    }; 
}; 
const mapDispatchToProps = dispatch => { 
    return { 
    onDeposit: amount => dispatch(depositIntoAccount(amount)), 
    }; 
}; 
const BankAppContainer = connect(mapStateToProps, mapDispatchToProps)(BankApp); 

这是我的<BankApp />组分,其从BankAppContainer接收道具:

class BankApp extends React.Component { 
    state = { 
    amount: 0 
    }; 

    onInputChange = e => { 
    const amount = e.target.value; 
    this.setState({ amount }); 
    }; 

    onDeposit = e => { 
    e.preventDefault(); 
    this.props.onDeposit({ 
     amount: parseFloat(this.state.amount, 10) 
    }); 
    this.setState({ amount: 0 }); 
    }; 

    render() { 
    return (
      <form> 
      <input 
       type="text" 
       onChange={this.onInputChange} 
       placeholder="add num" 
       value={this.state.amount} 
      /> 
      <br /> 
      <div> 
       <br /> 
       <button onClick={this.onDeposit}>deposit</button> 
       <button>withdraw</button> 
      </div> 
      </form> 

这是我的动作创建者存款帐户帐户:

export const depositIntoAccount = amount => ({ 
    type: "DEPOSIT_INTO_ACCOUNT", 
    amount 
}); 

,这是我的应用程序减速机:

export default (state = { balance: 0 }, action) => { 
    switch (action.type) { 
    case "DEPOSIT_INTO_ACCOUNT": 
     return { 
     balance: state.balance + parseFloat(action.amount) 
     }; 

当我deposit点击我派遣depositIntoAccount行动,但我console.log(bankStore.getState().balance)现在Object {balance: null}


===========解决方案如下:

您在对象错误的动作发送。

this.props.onDeposit({ 
    amount: parseFloat(this.state.amount, 10) 
}); 

这应该是

this.props.onDeposit(parseFloat(this.state.amount, 10)); 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)