gpt4 book ai didi

javascript - 将 Redux Saga 与 React 结合使用时出现此错误 .. Uncaught TypeError : getPosts is not a function

转载 作者:行者123 更新时间:2023-11-30 06:15:40 25 4
gpt4 key购买 nike

尝试学习如何将 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'));

Action 创作者:

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

reducer :

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....

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

谢谢!

最佳答案

您当前拥有的代码实际上并未将 getPosts 操作分派(dispatch)给您的 reducer 。

将 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 中找到很好的文档。

关于javascript - 将 Redux Saga 与 React 结合使用时出现此错误 .. Uncaught TypeError : getPosts is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56350117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com