微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

增量计数器在使用 Redux

如何解决增量计数器在使用 Redux

我正在尝试在 react-native 中使用 redux一个非常基本的增量计数器。我已经通过理解 redux 文档中的所有内容编写了我的所有代码。但是我的增量计数器仍然不起作用,我不知道为什么。

我有 4 个文件夹:[actions、components、containers、reducers]

和 1 个主文件:app.js

Actions 文件夹有 2 个文件:actionType.js 和 index.js

actionType.js:

export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";

index.js:

import {INCREMENT,DECREMENT} from "./actionType";
export const increaseAction = (step) => {
    return {
        type: INCREMENT,step: step,}
}
export const decreaseAction = (step) => {
    return {
        type: DECREMENT,}
}

components 文件夹只有一个文件:CounterComponent.js

import React from "react";
import { View,Text,TouchableOpacity } from "react-native";

export default class CounterComponent extends React.Component {
    render() {
        return (
            <View style={{flex: 1,marginTop: 50}}>
                <View style={{ flexDirection: "row",justifyContent: "space-around" }}>
                    <TouchableOpacity onPress={() => {this.props.onIncrement(1)}}>
                        <Text>INC</Text>
                    </TouchableOpacity >
                    <Text>{this.props.times}</Text>
                    <TouchableOpacity onPress={() => {this.props.onDecrement(1)}}>
                        <Text>DEC</Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}

Container 文件夹有 1 个文件:CounterContainer.js:

import { connect } from "react-redux";
import CounterComponent from "../components/CounterComponent"
import { increaseAction } from "../actions/index"
import { decreaseAction } from "../actions/index"

const mapStatetoProps = (state) => {
    console.log(state.counterReducers);
    return {times: state.counterReducers ? state.counterReducers : 0}
}

const mapdispatchToProps = (dispatch) => {
    return {
        onDecrement: (step) => {dispatch(decreaseAction(step))},onIncrement: (step) => {dispatch(increaseAction(step))}
    }
}
export default connect(mapStatetoProps,mapdispatchToProps)(CounterComponent);

Reducer 有 1 个文件:counterReducer.js:

import {INCREMENT,DECREMENT} from "../actions/actionType";    
const counterReducers = (times = 0,action) => {
    switch(action.type) {
        case INCREMENT: return ++times;
        case DECREMENT: return --times;
        default: return times;
    }
}
export default counterReducers;

最后是主文件:App.js:

import React from 'react';
import {createStore} from "redux";
import { Provider } from "react-redux";
import  counterReducers from "./reducers/counterReducer";
import CounterContainer from "./containers/CounterContainer"
let store = createStore(counterReducers)
export default class App extends React.Component {
  render() {
  return(
    <Provider store={store}><CounterContainer /></Provider>
  );
  }
}

我知道我为一个简单的问题发布了很多代码,但我真的试图找出我的代码的问题,但找不到。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。