我正在尝试使用react-redux
增加和减少反应中的状态值。我添加了动作,容器,减速器。但我不知道如何订阅increment
和decrement
这里的行动是我的代码
我想在用户点击按钮
时增加和减少该值这是我的代码 http://codepen.io/anon/pen/jVjMXv?editors=1010
const abc= (state=0,action) => {
console.log(action.type)
switch(action.type){
case 'INCREMENT':
return state +1
case 'DECREMENT':
return state -1
Default :
return state;
}
}
const {createStore,bindActionCreators} =Redux;
const {Provider,connect} =ReactRedux;
const store = createStore(abc);
class First extends React.Component {
constructor (){
super();
this.state ={
digit :0
}
}
inc (){
console.log('ince')
}
dec (){
console.log('dec')
}
render(){
return (
<div>
<button onClick={this.inc.bind(this)}>INCREMENT</button>
<p>{this.state.digit}</p>
<button onClick={this.dec.bind(this)}>DECREMENT</button>
</div>
)
}
}
const actions = {
increment: () => {
return {
type: 'INCREMENT',
}
},
decrement: () => {
return {
type: 'DECREMENT',
}
}
};
const AppContainer = connect(
function mapStateToProps(state) {
return {
digit: state
};
},
function mapDispatchToProps(dispatch) {
return bindActionCreators(actions, dispatch);
}
)(First);
ReactDOM.render(
<Provider store={store}>
<First/>
</Provider>
,document.getElementById('root'))
答案 0 :(得分:2)
您需要进行大量更改
首先:由于您要将第一个组件连接到状态,并将操作作为AppContainer连接,因此您需要在DOM中呈现它
MaxHeight
第二次:您正在调度操作<Button x:Name="button1" VerticalAlignment="Top" Content="Button">
<Button.Flyout>
<Flyout Placement="Right">
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="MaxHeight" Value="Infinity" />
</Style>
</Flyout.FlyoutPresenterStyle>
<Grid Name="PopupGrid" Background="Aqua" />
</Flyout>
</Button.Flyout>
</Button>
和ReactDOM.render(
<Provider store={store}>
<AppContainer/>
</Provider>
,document.getElementById('root'))
,并且您正在处理INC
,DEC
在reducer中
第三:你应该渲染你从redux获得的状态而不是像
那样的组件状态INCREMENT
第四:
通过DECREMENT
,{this.props.digit}
完整代码
this.props.increment()
<强> Here is a working codepen 强>
答案 1 :(得分:0)
非常简单的INC和DEC代码:道具和状态
完整代码:
class APP extends Component
{
constructor(props)
{
super(props)
this.state ={
digit: 0
}
this.onIncrement = this.onIncrement.bind(this);
this.onDecrement = this.onDecrement.bind(this);
}
onIncrement()
{
this.setState({
digit: this.state.digit + 1
)}
}
onDecrement()
{
this.setState({
digit: this.state.digit - 1
)}
}
render()
{
return(<p>{this.state.digit}</p>
<button type="button" onClick={this.onIncrement}> + </button>
<button type="button" onClick={this.onDecrement}> - </button>)
}
}
导出默认APP;