我是新来的反应者,只了解redux的概念而无需使用redux thunk。请参见下面的代码
// app.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
import * as actions from './actions'
class App extends Component {
render() {
return (
<div>
<button onClick={this.props.fetchData}>Show Data</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
}
}
const mapDispatchToProps = dispatch => {
return {
fetchData: () => dispatch(actions.fetchDataHandler)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import {createStore} from 'redux';
import Data from './reducers';
import {Provider} from 'react-redux';
const store = createStore(Data)
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
registerServiceWorker();
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
}
//reducers-index.js
// default state
const defaultState = {
data: null
}
let data;
export default data = (state=defaultState, action) => {
switch(action.type){
case "FETCH_DATA":
return {
...state,
data: action.payload
}
default:
return{
...state
}
}
}
文件夹结构为
src
actions
index.js
reducers
index.js
app.js
我没有使用redux thunk,当单击按钮时,它将调用fetchData,后者将调用actions.fetchDataHandler
因此,在控制台上,它应该收到一条消息,提示“打到这里”,但它不起作用。
对不起,如果我不能正确理解redux概念。
答案 0 :(得分:1)
在正常的redux流中,动作应该是纯对象,即动作创建者必须返回一个纯对象,但是在您的情况下,由于您不需要使用redux-thunk之类的中间件,因此您无法编写像
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
}
一般的方法是
export const fetchDataHandler = e => {
console.log("hit here");
return {
type: 'MY_ACTION'
}
}
但是,如果您配置redux-thunk
之类的中间件,则可以在动作创建者之内拥有一个异步动作,例如
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
API.call().then((res) => {
dispatch({ type: 'API_SUCCESS', payload: res });
});
}
您的mapDispatchToProps也未在分派中调用该操作,您可能会这样写
const mapDispatchToProps = dispatch => {
return {
fetchData: () => dispatch(actions.fetchDataHandler())
}
}
或
const mapDispatchToProps = {
fetchData: actions.fetchDataHandler
}