我在调度操作时遇到问题,并假设在redux
中更新我的状态。
这是我的主页组件。我可以得到计算器余额的当前状态。
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Text, ScrollView, Button } from "react-native";
import * as reducerActions from "../../store/actions/calculator";
function Homepage() {
const balance = useSelector((state) => state.calculator.balance);
const dispatch = useDispatch();
console.log(balance);
return (
<ScrollView>
<Text>Balance:{balance}</Text>
<Button
title="Add to Cart"
onPress={() => {
dispatch(reducerActions.DepositMoney(10));
}}
/>
</ScrollView>
);
}
export default Homepage;
这是我的操作组件:问题是它没有调用我的reducer。当我按下按钮时,它会记录值10。
export const DEPOSIT = "DEPOSIT";
export const DepositMoney = (amount) => {
return { type: DEPOSIT, payload: amount };
};
这是我的减速器组件:
import { DEPOSIT } from "../actions/calculator";
const initialState = {
balance: 0,
};
export default (state = initialState, action) => {
switch (action.Type) {
case DEPOSIT:
console.log("reducer");
console.log(action.payload);
return { balance: state.balance + action.payload };
case "WITHDRAW":
return { balance: state.balance - action.payload };
}
return state;
};
这就是我在app.js
中设置redux
的方式
import React, { useState } from "react";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import { AppLoading } from "expo";
import * as Font from "expo-font";
import ReduxThunk from "redux-thunk";
import productsReducer from "./store/reducers/products";
import ShopNavigator from "./navigation/ShopNavigator";
import calculatorReducer from "./store/reducers/calculator";
import { composeWithDevTools } from "redux-devtools-extension";
const rootReducer = combineReducers({
products: productsReducer,
calculator: calculatorReducer,
});
//composewithdevtools should be taken out for production
//const store = createStore(rootReducer, composeWithDevTools());
const store = createStore(
rootReducer,
composeWithDevTools(),
applyMiddleware(ReduxThunk)
);
const fetchFonts = () => {
return Font.loadAsync({
"open-sans": require("./assets/fonts/OpenSans-Regular.ttf"),
"open-sans-bold": require("./assets/fonts/OpenSans-Bold.ttf"),
});
};
export default function App() {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => {
setFontLoaded(true);
}}
/>
);
}
return (
<Provider store={store}>
<ShopNavigator />
</Provider>
);
}
@Christian是对的,但缺少一点。
在进行更改之前必须复制状态。
您也可以这样做。
export default (state = initialState, {type,payload}) => {
switch (type) {
case DEPOSIT:
console.log("reducer");
console.log(payload);
return { ...state, balance: state.balance + payload };
case "WITHDRAW":
return {...state, balance: state.balance - payload };
}
return state;
};
这太傻了。以下行错误:
switch (action.Type) {
应该是:
switch (action.type) {