【问题标题】:React Redux using Hooks使用 Hooks 反应 Redux
【发布时间】: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


    【解决方案1】:

    就像错误消息提示一样,您需要添加redux-thunk 才能使用dispatch with functions。阅读它here

    根据第一个例子,将store.js中的代码改成:

    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import reducers from './reducers/index';
    
    
    export const store = createStore(reducers, applyMiddleware(thunk));
    

    【讨论】:

    • 或者@AsafAviv 的建议,也许更好
    • 他的建议很好,但你的例子更好。我的示例非常基础,真实的应用程序会有异步请求。
    • @myTest532myTest532 您可以混合我们的建议:使用函数调度进行异步状态更新,并返回一个对象进行同步更新
    • 在这两种情况下,你还应该看看官方的 Redux Toolkit,它会预先配置 redux-thunk,还会自动为你创建非 thunk 动作创建器(并且还会创建一个您在那里编写的更多代码已过时)。最好遵循现在从一开始就教授 Redux Toolkit 的官方 Redux 教程:redux.js.org/tutorials/essentials/part-1-overview-concepts
    【解决方案2】:

    如果您不执行任何异步操作,则不需要返回函数,因此您只需更改动作创建者以返回动作对象。

    export const depositMoney = amount => ({
      type: 'deposit',
      payload: amount,
    })
    
    export const withdrawMoney = amount => ({
      type: 'withdraw',
      payload: amount,
    })
    

    如果您确实需要在动作创建器中执行异步操作,您可以使用redux-thunk middleware

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2018-03-07
      • 1970-01-01
      • 2020-01-30
      相关资源
      最近更新 更多