我正在尝试在我的 React 应用程序中使用 redux-saga,但我仍然遇到此错误:
Actions must be plain objects. Use custom middleware for async actions.
错误是:
15 | changeText = event => {
> 16 | this.props.changeText(event.target.value);
17 | };
这是我的代码:
App.js
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as actions from "./redux/actions";
import { initStore } from "./redux/store";
class App extends Component {
changeText = event => {
this.props.changeText(event.target.value);
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>react-redux-saga</p>
<input type="text" onChange={e => this.changeText(e)} />
<hr />
<p>{this.props.changeTextReducer.text}</p>
</header>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
changeText: bindActionCreators(actions.changeText, dispatch),
};
};
export default connect(
({ changeTextReducer }) => ({ changeTextReducer }),
mapDispatchToProps,
)(App);
index.js
import changeTextReducer from "./redux/changeTextReducer";
import rootSaga from "./redux/sagas";
export const reducer = combineReducers({
changeTextReducer,
});
const sagaMiddleware = createSagaMiddleware();
const store = createStore(reducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root"),
);
actions.js
export function changeText(value) {
return function(dispatch) {
dispatch({
type: "CHANGE_TEXT",
value,
});
};
}
changeTextReducer.js
const initialState = {
text: "",
};
export default (state = initialState, action) => {
switch (action.type) {
case "CHANGE_TEXT":
return {
...(state || {}),
text: action.payload,
};
default:
return state;
}
};
传奇.js
import { put, takeEvery, all, call } from "redux-saga/effects";
export const delay = ms => new Promise(res => setTimeout(res, ms));
export function* helloSaga() {
console.log("Hello Sagas!");
}
export function* changeTextAsync() {
yield call(delay, 5000);
yield put({ type: "CHANGE_TEXT", payload: "" });
}
export function* watchChangeTextAsync() {
yield takeEvery("CHANGE_TEXT", changeTextAsync);
}
export default function* rootSaga() {
yield all([helloSaga(), watchChangeTextAsync()]);
}
我很乐意提供所有帮助。我和它战斗了大约两天,但仍然没有解决方案。我试图查找,但我仍然有这个错误。
最佳答案
改变你的行动。它只能接收对象,不能调用函数:
actions.js
export function changeText(value) {
type: "CHANGE_TEXT",
payload: {text:value},
}
关于javascript - React-Redux-Saga : Actions must be plain objects. 使用自定义中间件进行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330386/