redux 存储中的更新量但不在组件状态中。我在做什么错?
组件状态下的金额为 0
成分
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux';
class testComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'shirt',
quantity: 2,
rate: 4,
amount: 0,
}
}
computeAmount() {
this.props.dispatch({
type: 'COMPUTE_AMOUNT',
paylod: { rate: this.state.rate, quantity: this.state.quantity }
})
}
render() {
return (
<div>
AMOUNT IN REDUX = {this.props.amount}
<div>
<input value={this.state.name} />
quantity <input value={this.state.quantity} />
rate <input value={this.state.rate} />
amount <input value={this.state.amount} />
</div>
AMOUNT IN STATE = {this.state.amount}
<div> <button onClick={(e) => this.computeAmount(e)} >Compute Amount</button> </div>
</div>
);
}
}
testComponent.propTypes = {
dispatch: PropTypes.func.isRequired,
amount: PropTypes.number.isRequired
}
const mapStateToProps = (state) => {
return {
amount: state.rootReducer.testReducer.amount
}
}
export default connect(mapStateToProps)(testComponent)
减速器
import update from 'immutability-helper';
let initialState = {amount : 0}
const testReducer = (state = initialState, action) => {
switch (action.type) {
case 'COMPUTE_AMOUNT':
action.paylod.amount = action.paylod.rate * action.paylod.quantity
//Try 1
return { ...state, ...action.paylod }
//Try 2
// return update(state, { $set: action.paylod });
//Try 3
//return update(state, { $merge: action.paylod });
default:
return state;
}
}
export default testReducer;
谢谢@Mohamed Binothman
您的 amount 值未连接到 Redux 状态,这就是问题所在。要使您的组件状态与 Redux 状态同步,您需要执行以下操作:
1- 声明您需要从连接上的 redux 状态获取的值。
const mapStateToProps = (store) => {
return {
amount: store.yourReducer.amount
}
}
testComponent = connect(mapStateToProps)(testComponent)
2 : 添加 componentWillReceiveProps 到你的组件
componentWillReceiveProps(nextProps){
if (this.state.amount !== nextProps.amount) {
this.setState({amount: nextProps.amount})
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句