【发布时间】:2021-08-11 01:02:44
【问题描述】:
我正在尝试使用 Hooks 创建我的第一个 react redux。
我的 src 文件夹中有一个 state 文件夹。 在我的状态文件夹中,我有另一个名为 reducer 的文件夹和一个 accountReducer.js 文件 accountReducer.js:
const reducer = (state = 0, action) => {
switch(action.type) {
case "deposit":
return state + action.payload;
case "withdraw":
return state - action.payload;
default:
return state;
}
}
export default reducer;
另外,我有一个 index.js 来组合和导出我的减速器
import { combineReducers } from "redux";
import AccountReducer from './accountReducer';
const reducers = combineReducers({
account: AccountReducer
});
export default reducers;
在状态文件夹中,我有我的 store.js
import { createStore } from "redux";
import reducers from './reducers/index';
export const store = createStore(
reducers,
{}
);
我还有一个 action-creator 文件夹,其中包含一个 index.js 文件用于我的操作
export const depositMoney = (amount) => {
return (dispatch) => {
dispatch({
type: "deposit",
payload: amount
});
}
}
export const withdrawMoney = (amount) => {
return (dispatch) => {
dispatch({
type: "withdraw",
payload: amount
});
}
}
另外,在状态文件夹中,我有一个 index.js 来导出我的 actionCreators
export * as actionCreators from "./action-creators/index";
在主 index.js 文件中,我为我的商店创建了一个 Provider
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from "react-redux";
import { store } from './state/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
最后,我在 App.js 中测试我的 redux
import { useSelector, useDispatch } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators } from './state/index';
function App() {
const account = useSelector((state) => state.account);
const dispatch = useDispatch();
const { depositMoney, withdrawMoney } = bindActionCreators(actionCreators, dispatch);
return (
<div className="App">
<h1>{account}</h1>
<button onClick={() => depositMoney(500)}>Deposit</button>
<button onClick={() => withdrawMoney(250)}>Withdraw</button>
</div>
);
}
export default App;
当我点击存款或提款时,它会返回:
Error: Actions must be plain objects. Instead, the actual type was: 'function'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.
我的代码中缺少什么?
【问题讨论】:
标签: reactjs redux react-redux