问题描述
我正在尝试在 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 (将#修改为@)