【问题标题】:When Using Redux Saga with React Get This Error .. Uncaught TypeError: getPosts is not a function将 Redux Saga 与 React 一起使用时会出现此错误 .. Uncaught TypeError: getPosts is not a function
【发布时间】:2019-05-28 21:11:17
【问题描述】:

尝试学习如何将 Redux Sagas 与 React 结合使用。把一个简单的例子放在一起,但它对我不起作用。

我的 App.js 文件中的代码:

const sagaMiddleware = createSagaMiddleWare();

const store = createStore(
  reducers,
  applyMiddleware(sagaMiddleware)
)

sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));

动作创建者:

 export const getPosts = () => {
        return  {
           type: 'GET_POSTS'
        }
     };

减速机:

const combineReducers = (state= {}, action) => {
     switch (action.type) {
       case 'GET_POSTS':
         return { ...state, loading: true};
       default:
         return state;
        }
      }

   export default combineReducers;

我的 Button 组件应该在其中调用 onClick 操作

const ButtonContainer = (getPosts) => (
     <button onClick={() => getPosts()}>Get Posts</button>
)

const mapDispatchToProps = {
  getPosts: getPosts
}

export default connect(null, mapDispatchToProps)(ButtonContainer);

问题是我在页面加载时收到此错误。

Uncaught TypeError: getPosts is not a function....

理解错误在说什么,它获取的是对象而不是函数,但不确定我需要做什么才能使其工作。

谢谢!

【问题讨论】:

    标签: javascript reactjs redux redux-saga dispatch


    【解决方案1】:

    您当前拥有的代码实际上并未将 getPosts 操作分派给您的减速器。

    将 mapDispatchToProps 更改为:

    const mapDispatchToProps = dispatch => {
      getPosts: bindActionCreators(getPosts, dispatch)
    }
    

    您还需要:

    import { bindActionCreators, Dispatch } from "redux"
    

    还将您的 ButtonContainer 更改为:

    const ButtonContainer = props => (
         <button onClick={() => props.getPosts()}>Get Posts</button>
    )
    

    更多关于调度的信息可以在this好的文档中找到。

    【讨论】:

    • 感谢您的回复。我尝试了上面的代码,现在我得到了错误:Uncaught TypeError: getPosts is not a function。有什么想法吗?同时,我正在研究您在上面发布的链接并尝试解决此问题。
    • 我认为这是因为您的按钮组件输入参数是道具而不是getPosts。我已经更新了我的答案。
    • 天啊!愚蠢的错误,解决了它。非常感谢!
    • 你知道主要问题是什么,我添加了 props.getPosts 并恢复到我的原始代码,它仍然有效:-)
    • 没问题@sayayin。很高兴您的问题现已解决:)
    猜你喜欢
    • 2018-12-31
    • 2023-02-17
    • 2020-01-03
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多