【发布时间】:2019-03-12 10:36:38
【问题描述】:
我正在学习如何使用 reactjs、redux、react-redux 和 redux-saga。我在我的公共 github 存储库中对此进行了尝试,可在此处找到:
https://github.com/latheesan-k/react-redux-saga/tree/5cede54a4154740406c132c94684aae1d07538b0
我的store.js:
import { compose, createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import reducer from "./reducers";
import mySaga from "./sagas";
const sagaMiddleware = createSagaMiddleware();
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// TODO: Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
})
: compose;
const storeEnhancer = composeEnhancers(applyMiddleware(sagaMiddleware));
export default createStore(reducer, storeEnhancer);
sagaMiddleware.run(mySaga);
我的actions.js
export const HELLO_WORLD_REQUEST = "HELLO_WORLD_REQUEST";
export const HELLO_WORLD_RESPONSE = "HELLO_WORLD_RESPONSE";
export const HELLO_WORLD_ERROR = "HELLO_WORLD_ERROR";
export const helloWorldRequest = () => ({ type: HELLO_WORLD_REQUEST });
export const helloWorldResponse = text => ({ type: HELLO_WORLD_RESPONSE, text });
export const helloWorldError = error => ({ type: HELLO_WORLD_ERROR, error });
还有我的 sagas.js
import { put, takeLatest } from "redux-saga/effects";
import { HELLO_WORLD_REQUEST, helloWorldResponse, helloWorldError } from "./actions";
function* runHelloWorldRequest(action) {
try {
// TODO: real api call here
yield put(helloWorldResponse("Hello from react-redux-saga :)"));
} catch (e) {
yield put(helloWorldError(e));
}
}
export default function* mySaga() {
yield takeLatest(HELLO_WORLD_REQUEST, runHelloWorldRequest);
}
还有我的 helloWorldReducer.js
import { HELLO_WORLD_RESPONSE } from "../actions";
export default (state = "", { type, text }) => {
switch (type) {
case HELLO_WORLD_RESPONSE:
return text;
default:
return state;
}
};
这就是将它们放在我的App 组件上的方式:
class App extends Component {
componentDidMount() {
this.props.helloWorldRequest();
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>{this.props.responseText}</p>
</header>
</div>
);
}
}
const mapStateToProps = state => ({ responseText: state.helloWorldReducer });
const mapDispatchToProps = dispatch => bindActionCreators({ helloWorldRequest }, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
这很好用,但这是我试图理解的奇怪行为。为了从状态中获取响应值并将其映射到道具中,我必须这样做:
const mapStateToProps = state => ({ responseText: state.helloWorldReducer });
根据我在 react devtools 中看到的:
处理请求并生成响应后的通知;生成的状态对象包含一个名为 helloWorldReducer 的字段。
这是从哪里来的?
我认为这个字段名称应该被称为 text。
附:对不起,很长的帖子;还在学习 react-redux-saga,所以我不知道我的代码的哪一部分与手头的问题相关。
【问题讨论】:
标签: reactjs redux react-redux redux-saga