如何在本机中使用thunk?

问题描述 投票:0回答:1

我正在学习redux,

我只想模拟从服务器获取数据,所以我用setTimeout()处理它,

但是有错误

错误:动作必须是普通对象。使用自定义中间件进行异步动作。

尽管我安装了redux-thunk并不能解决问题!

这里的代码

../ actions / userActions.js

const setName = name => {
  return dispatch => {
    setTimeout(() => {
      dispatch({
        type: 'SET_NAME',
        payload: name,
      });
    }, 2000);
  };
};

const setAge = age => {
  return {
    type: 'SET_AGE',
    payload: age,
  };
};

export {setName, setAge};

./ reducers / userReducers.js

const userReducer = (
  state = {
    name: 'Max',
    age: 27,
  },
  action,
) => {
  switch (action.type) {
    case 'SET_NAME':
      state = {
        ...state,
        name: action.payload,
      };
      break;
    case 'SET_AGE':
      state = {
        ...state,
        age: action.payload,
      };
      break;
  }
  return state;
};

export default userReducer;

./ store.js

import {applyMiddleware, combineReducers, compose, createStore} from 'redux';
import thunk from 'redux-thunk';
import mathReducer from '../reducers/mathReducer';
import userReducer from '../reducers/userReducer';

const store = createStore(
  combineReducers(
    {math: mathReducer, user: userReducer},
    // applyMiddleware(thunk) not work :]
    compose(applyMiddleware(thunk)), //same :]
  ),
);

export default store;

App.js

class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Main changeUsername={() => this.props.setName('Oliver')} />
        <User username={this.props.user.name} />
      </View>
    );
  }
}



const mapStateToProps = state => {
  return {
    user: state.user, //user is a key == userReducer
    math: state.math,
  };
};

const mapDispatchToProps = dispatch => {
  // to excute the actions we want to invok
  return {
    setName: name => {
      dispatch(setName(name));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);
javascript reactjs redux react-redux redux-thunk
1个回答
0
投票

取消注释中间线。

const store = createStore(
  combineReducers(
    {math: mathReducer, user: userReducer},
    applyMiddleware(thunk),
    compose(applyMiddleware(thunk)), //same :]
  ),
);

© www.soinside.com 2019 - 2024. All rights reserved.