在Redux中,如果有两个计数器组件要绑定到Redux Store中的两个属性,您不必编写两次reducer和mapStateToProps。
首先,您可以在reducer中定义两个属性,例如counter1和counter2,分别对应两个计数器的状态。在reducer中,您可以处理两个计数器的不同操作,例如增加、减少等。
接下来,在mapStateToProps中,您可以使用对象的解构语法来获取counter1和counter2的值,并将它们作为props传递给相应的计数器组件。这样,两个计数器组件就可以分别访问它们所需的属性。
示例代码如下:
// reducer.js
const initialState = {
counter1: 0,
counter2: 0
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT_COUNTER1':
return {
...state,
counter1: state.counter1 + 1
};
case 'DECREMENT_COUNTER1':
return {
...state,
counter1: state.counter1 - 1
};
case 'INCREMENT_COUNTER2':
return {
...state,
counter2: state.counter2 + 1
};
case 'DECREMENT_COUNTER2':
return {
...state,
counter2: state.counter2 - 1
};
default:
return state;
}
};
export default reducer;
// mapStateToProps.js
const mapStateToProps = (state) => {
const { counter1, counter2 } = state;
return {
counter1,
counter2
};
};
export default mapStateToProps;
然后,您可以在两个计数器组件中使用connect函数来连接Redux Store,并将mapStateToProps作为参数传递给connect函数。这样,两个计数器组件就可以访问它们所需的属性。
示例代码如下:
// Counter1.js
import React from 'react';
import { connect } from 'react-redux';
const Counter1 = ({ counter1, incrementCounter1, decrementCounter1 }) => {
return (
<div>
<h2>Counter 1: {counter1}</h2>
<button onClick={incrementCounter1}>Increment</button>
<button onClick={decrementCounter1}>Decrement</button>
</div>
);
};
const mapDispatchToProps = (dispatch) => {
return {
incrementCounter1: () => dispatch({ type: 'INCREMENT_COUNTER1' }),
decrementCounter1: () => dispatch({ type: 'DECREMENT_COUNTER1' })
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter1);
// Counter2.js
import React from 'react';
import { connect } from 'react-redux';
const Counter2 = ({ counter2, incrementCounter2, decrementCounter2 }) => {
return (
<div>
<h2>Counter 2: {counter2}</h2>
<button onClick={incrementCounter2}>Increment</button>
<button onClick={decrementCounter2}>Decrement</button>
</div>
);
};
const mapDispatchToProps = (dispatch) => {
return {
incrementCounter2: () => dispatch({ type: 'INCREMENT_COUNTER2' }),
decrementCounter2: () => dispatch({ type: 'DECREMENT_COUNTER2' })
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Counter2);
通过以上方式,您可以实现两个计数器组件与Redux Store中的两个属性的绑定,而无需重复编写reducer和mapStateToProps。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云